2017-08-14 7 views
0

に変更リストを渡す:私は木を成長させるための機能を書いていた二分木の各ノード

def collect_append(collect,split): 
collect.append(split) 
return collect   


def tree(string,passwords,collect): #collect is a list and passwords is also a list 

matching_list = [] 
match = 0 
if len(string)==0: 
    print(collect) 
    return 0 
for j in passwords: 
    for i in range(min(len(j),len(string))): 
    if string[i]!=j[i]: 
     break 
else : 
    matching_list.append(j) 
    match = match + 1 
if match == 0: 
    return 1 
else: 
    for split in matching_list: 
    x =tree(string.strip(split),passwords,collect_append(collect,split)) 
return x 

私の質問はmatching_listにおける各分割(2言う)のために、私は別の文字列を追加したい、ですその時点での既存のリスト(つまり、2つのバージョンのリストが必要です)。

この場合、私が使用するcollect_append関数は、forループの最初の反復でリストを変更し、それをさらなる反復に使用しています。私が欲しいのは、パラメータを恒久的に変更することなく、リストのcollectを変更するだけです。これを行う方法はありますか?

+0

ようこそStackOverflow。ヘルプドキュメントの投稿ガイドラインを読み、それに従ってください。 [最小、完全で検証可能な例](http://stackoverflow.com/help/mcve)がここに適用されます。 MCVEコードを投稿して問題を正確に記述するまでは、効果的にお手伝いすることはできません。 投稿したコードをテキストファイルに貼り付け、説明した問題を再現できるはずです。 – Prune

答えて

1

コードに2つの重大なエラーがあります。まず、このelse句が実行されることはありません:

for j in passwords: 
    for i in range(...): 
     if ...: 
      break 
else: 
    ... 

breakが内側forループ内にあるので、外側のループforのでelseが取られることはないbreakを介して出射されることはありません。第二に、これはあなたがやりたいことはありません:あなたはstringの先頭からsplitを削除しようとしているが、あなたはひどくそれをあざ、stringの両端からsplit内のすべての文字を削除している

string.strip(split) 

。ここではそれを正しく行うための一つの方法です:

string[len(split):] 

私は手足に出て行って、そして私はあなたがそれをやりたいと思う何をすべきか、あなたのコードを書き換えるつもりです:

def tree(string, passwords, collect): 

    length = len(string) 

    if length == 0: 
     return False 

    matching_list = [] 

    for j in passwords: 
     i = min(len(j), length) 

     if string[:i] == j[:i]: 
      matching_list.append(j) 

    if not matching_list: 
     return False 

    result = False 

    for split in matching_list: 
     local_collection = list([split]) 
     if split == string or tree(string[len(split):], passwords, local_collection): 
      collect.append(local_collection) 
      result = True 

    return result 

collection = [] 

print(tree('dogcatcher', ['cat', 'catch', 'cher', 'dog', 'dogcat', 'dogcatcher', 'er'], collection)) 

print(collection) 

OUTPUTあなたpasswords内の単語からstringを組み立てるためのすべての方法の木を与える

% python3 test.py 
True 
[['dog', ['cat', ['cher']], ['catch', ['er']]], ['dogcat', ['cher']], ['dogcatcher']] 
% 

+0

ありがとう!まさに私が望んでいたもの –

関連する問題