在python中通过树层次结构循环?

时间:2012-12-04 20:20:17

标签: python recursion tree

我是新来的,对python来说很新!

我们做了一个功课,我已经能够完成剩下的工作了,但还有一个问题: 如果我有这样的树层次结构:

root = [
    parent1 = [
        child1,
        child2 = [
            sub_child
        ]
        child3
    ],
    parent2 = [
        child1,
        child2
    ]
]

它们都是一个名为TreeHierarchyClass的类的实例,它们都有一个名称属性,如何找到我输入的名称?

我尝试使用for循环但是没有办法知道我需要多少?获得名称很简单:

name = input("Enter name: ")
if name == TreeHierarchyObject.name:
    print("Found it!")

但我如何循环对象?

2 个答案:

答案 0 :(得分:4)

你应该在这里使用简单的递归。 该方法稍微依赖于子对象如何附加到父对象。

如果它们位于self.children列表中,则可以使用此列表,我建议您这样做。 只需在类中定义以下方法:

def findObjectByName(self, name):
    if self.name == name:
        return self
    else:
        for child in self.children:
            match = child.findObjectByName(name)
            if match:
                return match

修改 要使此功能适用于任何属性,而不仅仅是名称,请改为使用getattr()

def findObject(self, attr, value):
    if getattr(self, attr) == value:
        return self
    else:
        for child in self.children:
            match = child.findObject(attr, value)
            if match:
                return match

只需致电root.findObjectByName("Sub Child!")或使用第二种方法:root.findObject("name", "Sub Child!")

答案 1 :(得分:1)

您可以使用recursion,也可以使用iteration。无论哪种方式都无关紧要。但是你需要一种策略来搜索树。

以下是一些通过图表的策略:

主要思想是不要经历两次相同的节点/叶子,这对于树来说是微不足道的,但是对于图形需要coloring

您可以使用一些设计模式,例如visitor模式,您可以向.visit()添加方法TreeHierarchyClass以访问其子节点,并按名称添加另一个方法以查找节点。

示例:

# imagine we got this class
class TreeHierarchyClass(object):
    def __init__(self, value):
        self.children = []
        self.value = value
        if self.value == 13:
            self.name = 'the lucky one.'
    def add(self, value):
        self.children.append(type(self)(value))

您可以访问所有节点:

def visit(tree):
    visited = set()
    nonvisited = set()
    nonvisited.update(tree.children)
    while nonvisited:
        item = nonvisited.pop()
        # already seen
        if item in visited:
            continue
        # mark item
        visited.add(item)
        yield item
        # add children
        nonvisited.update(item.children)

让我们构建一个示例树结构:

root = TreeHierarchyClass(0)

for i in range(10):
    root.add(i)

for i in range(10):
    root.children[1].add(i + 10)

现在让我们找一些项目:

def find(name):
    for item in visit(root):
        print 'checking item with value %d' % item.value,
        if getattr(item, 'name', None) == name:
            print '- found it.'
            break
        else:
            print '- nope, keep searching.'
    else:
        print 'Sorry, not found.'

find('the lucky one.')
find('the lost one.')

此示例将打印:

>>> find('the lucky one.')
checking item with value 7 - nope, keep searching.
checking item with value 0 - nope, keep searching.
checking item with value 1 - nope, keep searching.
checking item with value 12 - nope, keep searching.
checking item with value 2 - nope, keep searching.
checking item with value 9 - nope, keep searching.
checking item with value 19 - nope, keep searching.
checking item with value 3 - nope, keep searching.
checking item with value 11 - nope, keep searching.
checking item with value 4 - nope, keep searching.
checking item with value 14 - nope, keep searching.
checking item with value 5 - nope, keep searching.
checking item with value 6 - nope, keep searching.
checking item with value 15 - nope, keep searching.
checking item with value 8 - nope, keep searching.
checking item with value 16 - nope, keep searching.
checking item with value 13 - found it.
>>> find('the lost one.')
checking item with value 7 - nope, keep searching.
checking item with value 0 - nope, keep searching.
checking item with value 1 - nope, keep searching.
checking item with value 12 - nope, keep searching.
checking item with value 2 - nope, keep searching.
checking item with value 9 - nope, keep searching.
checking item with value 19 - nope, keep searching.
checking item with value 3 - nope, keep searching.
checking item with value 11 - nope, keep searching.
checking item with value 4 - nope, keep searching.
checking item with value 14 - nope, keep searching.
checking item with value 5 - nope, keep searching.
checking item with value 6 - nope, keep searching.
checking item with value 15 - nope, keep searching.
checking item with value 8 - nope, keep searching.
checking item with value 16 - nope, keep searching.
checking item with value 13 - nope, keep searching.
checking item with value 17 - nope, keep searching.
checking item with value 10 - nope, keep searching.
checking item with value 18 - nope, keep searching.
Sorry, not found.