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. 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). Does anyone know a more pythonic way of expressing this?
Here is a simplified version of our code - it is the definition of path_from_root
we are looking to improve:
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:
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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.