从项目组合列表创建树

时间:2011-10-11 13:41:36

标签: list tree combinations

我有n个列表A,B,C ......其中包含a,b,c ...元素。我正在使用它们来创建可能的组合列表(列表列表),这样第一个元素取自表A,第二个取自B等。将这个平面结构转换为遵循根的树的最佳方法是什么通过列表A的元素,每个元素都包含列表B等的所有元素,从而以根路径的形式创建每个可能的组合?

1 个答案:

答案 0 :(得分:3)

算法

1:从输入

开始

因此,如果您有[1, 2, 3][4, 5, 6][7, 8, 9]列表,那么您有this list of possible permutiations

所以我现在将浏览列表及其元素。所有代表您想要的树的路径。因此,如果所有内容都放入树中,我将能够找到节点1,然后转到4,然后在第三级找到7。如果我不这样做,我必须在那里添加。

paths = [
    [1, 4, 7], [1, 4, 8], [1, 4, 9], [1, 5, 7], [1, 5, 8], [1, 5, 9], [1, 6, 7], [1, 6, 8], [1, 6, 9], [2, 4, 7], [2, 4, 8], [2, 4, 9], [2, 5, 7], [2, 5, 8], [2, 5, 9], [2, 6, 7], [2, 6, 8], [2, 6, 9], [3, 4, 7], [3, 4, 8], [3, 4, 9], [3, 5, 7], [3, 5, 8], [3, 5, 9], [3, 6, 7], [3, 6, 8], [3, 6, 9]
]

class Tree(object):
    def __init__(self, node=None):
        self.node = node
        self.children = []

    def addChild(self, child):
        self.children.append(child)

    def toList(self):
        if len(self.children) > 0:
            return [self.node, [x.toList() for x in self.children]]
        else:
            return [self.node]

tree = Tree()

# iterate through the lists
for path in paths:
    subtree = tree

    for value in path:
        # check whether the current value already exists at this position in the tree
        found = False
        for child in subtree.children:
            if value == child.node:
                subtree = child
                found = True
                break

        # attach the leaf to the current position in the tree if needed
        if not found:
            newchild = Tree(node=value)
            subtree.addChild(newchild)
            subtree = newchild

        # use the found or created leaf as a position for the next value in the path-list

print tree.toList()

2:返回原始列表

如果树看起来是对称的,你也可以只切片树的层次,给你列表A,B和C.然后,你回到原点,可以建立树:< / p>

paths = [
    [1, 4, 7], [1, 4, 8], [1, 4, 9], [1, 5, 7], [1, 5, 8], [1, 5, 9], [1, 6, 7], [1, 6, 8], [1, 6, 9], [2, 4, 7], [2, 4, 8], [2, 4, 9], [2, 5, 7], [2, 5, 8], [2, 5, 9], [2, 6, 7], [2, 6, 8], [2, 6, 9], [3, 4, 7], [3, 4, 8], [3, 4, 9], [3, 5, 7], [3, 5, 8], [3, 5, 9], [3, 6, 7], [3, 6, 8], [3, 6, 9]
]

lists = [[]]*len(paths[0])
for i in xrange(len(paths[0])):
    lists[i] = set([])
    for l in paths:
        lists[i].add(l[i])

def iterate(listnumber):
    result = []
    for element in lists[listnumber]:
        if listnumber < len(lists)-1:
            result.append([element, iterate(listnumber+1)])
        else:
            result.append([element])
    return result

tree = iterate(0)

print tree

它遍历一堆列表(a,b,c)中的每一层,并将唯一成员存储在列表中。然后它有列表A,B,C并从中生成树。

结果

这是我得到的树,0是人工根。节点被“回收”,因为它们都具有相同的内容。 (用dot制作。)

http://wstaw.org/m/2011/10/11/tree.png