簡體   English   中英

從根到選定節點的樹路徑-Python方式

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

在python應用程序中,我們有一棵由TreeNode對象組成的樹,我們必須在TreeNode類上添加一個屬性,該屬性以列表的形式返回從樹根到該節點的路徑。 我們已經以一種簡單的遞歸方式實現了這一點,但是對於python來說,代碼看起來有些冗長(我們懷疑在python中有一種表達這種簡單算法的簡潔方法)。 有誰知道這種表達方式更Python化

這是我們代碼的簡化版本-它是我們希望改進的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)

下面是一些單元測試,它們顯示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)

更新:接受了一個明顯改善的答案,但是肯定仍然對表達它的任何其他方式感興趣。

我會這樣:

@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