代码之家  ›  专栏  ›  技术社区  ›  Fenil

将修改后的列表传递给二叉树的每个节点

  •  0
  • Fenil  · 技术社区  · 9 年前

    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 仅列出参数,而不永久更改。有办法做到这一点吗?

    1 回复  |  直到 9 年前
        1
  •  1
  •   cdlane    9 年前

    我看到你的代码中有两个严重错误。首先,这个 else 条款从未执行:

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

    break 在内部 for 对于 循环从未通过 所以 其他的

    string.strip(split)
    

    您正在尝试删除 split 从年初 string 但你正在删除中的所有字母 一串 ,严重擦伤。这里有一种正确的方法:

    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)
    

    输出

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

    给你一棵集合的树 一串 passwords .