2017-08-14 68 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

谢谢!正是我想要的 –