2017-08-14 70 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每個分割(比如二),我想添加不同的字符串在這一點上的現有名單(即我想要兩個版本的名單)。

在這種情況下,我使用的collect_append函數是在for循環的第一次迭代中修改列表,並將其用於進一步的迭代。我想要的只是修改collect列表僅用於參數,並且不會永久更改它。有沒有辦法做到這一點?

+0

歡迎來到StackOverflow。請閱讀並遵守幫助文檔中的發佈準則。 [最小,完整,可驗證的示例](http://stackoverflow.com/help/mcve)適用於此處。在發佈您的MCVE代碼並準確描述問題之前,我們無法爲您提供有效的幫助。 我們應該能夠將發佈的代碼粘貼到文本文件中,並重現您描述的問題。 – Prune

回答

1

我在代碼中看到兩個嚴重錯誤。首先,永遠不會執行這else子句:

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

由於break是在內部for環,外for循環從未經由break所以else從未採取退出。其次,這並不做你想做的:

string.strip(split) 

你試圖從的string開始刪除split但你在splitstring兩端刪除所有信件,嚴重擦傷了。這裏是做正確的一種方式:

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

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

給你的所有組裝自言stringpasswords方式的樹。

+0

謝謝!正是我想要的 –