简体   繁体   English

从根到选定节点的树路径-Python方式

[英]Tree Path from Root to Selected Node - The Pythonic Way

In a python application we have a tree made up of TreeNode objects, and we had to add a property on the TreeNode class that returns the path from the tree root to that node as a list. 在python应用程序中,我们有一棵由TreeNode对象组成的树,我们必须在TreeNode类上添加一个属性,该属性以列表的形式返回从树根到该节点的路径。 We have implemented this in a simple recursive way, however the code looks a little verbose for python (we suspect there is a terser way of expressing a simple algorithm like this in python). 我们已经以一种简单的递归方式实现了这一点,但是对于python来说,代码看起来有些冗长(我们怀疑在python中有一种表达这种简单算法的简洁方法)。 Does anyone know a more pythonic way of expressing this? 有谁知道这种表达方式更Python化

Here is a simplified version of our code - it is the definition of path_from_root we are looking to improve: 这是我们代码的简化版本-它是我们希望改进的path_from_root的定义:

class TreeNode(object):

    def __init__(self, value, parent=None):
        self.value = value
        self.parent = parent

    @property
    def path_from_root(self):
        path = []
        _build_path_from_root(self, path)
        return path


def _build_path_from_root(node, path):
    if node.parent:
        _build_path_from_root(node.parent, path)
    path.append(node)

Below are some unit tests that show how path_from_root works: 下面是一些单元测试,它们显示path_from_root工作方式:

class TreePathAsListTests(unittest.TestCase):

    def setUp(self):
        self.root = TreeNode(value="root")
        self.child_1 = TreeNode(value="child 1", parent=self.root)
        self.child_2 = TreeNode(value="child 2", parent=self.root)
        self.leaf_1a = TreeNode(value="leaf 1a", parent=self.child_1)

    def test_path_from_root(self):
        self.assertEquals([self.root, self.child_1, self.leaf_1a], self.leaf_1a.path_from_root)
        self.assertEquals([self.root, self.child_2], self.child_2.path_from_root)
        self.assertEquals([self.root], self.root.path_from_root)

Update: Accepted an answer that was a clear improvement, but definitely still interested in any other ways of expressing this. 更新:接受了一个明显改善的答案,但是肯定仍然对表达它的任何其他方式感兴趣。

I would do it this way: 我会这样:

@property
def path_from_root(self):
    if self.parent:
        return self.parent.path_from_root + [self]
    return [self]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM