Last active
December 22, 2015 04:18
-
-
Save omaraboumrad/6415677 to your computer and use it in GitHub Desktop.
simple bidirectional tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class NodeList(list): | |
def __init__(self, root, items): | |
self.root = root | |
super(NodeList, self).__init__(items) | |
def append(self, item): | |
item._parent = self.root | |
super(NodeList, self).append(item) | |
class Node(object): | |
def __init__(self, name, parent=None, children=None): | |
self.name = name | |
self.children = children | |
self._parent = None | |
self.parent = parent | |
@property | |
def parent(self): | |
return self._parent | |
@parent.setter | |
def parent(self, value): | |
if value == self._parent: | |
return | |
if self._parent: | |
if self._parent.children: | |
self._parent.children.remove(self) | |
if value: | |
if value.children: | |
value.children.append(self) | |
else: | |
value.children = NodeList(value, [self]) | |
self._parent = value | |
def __repr__(self): | |
return 'N:{}'.format(self.name) | |
if __name__ == '__main__': | |
root = Node('root') | |
omar = Node('omar', parent=root) | |
joe = Node('joe', parent=root) | |
assert root.name == 'root' | |
assert len(root.children) == 2 | |
other = Node('other') | |
omar.parent = other | |
assert other.name == 'other' | |
assert len(other.children) == 1 | |
assert len(root.children) == 1 | |
last = Node('last') | |
other.children.append(last) | |
assert len(other.children) == 2 | |
assert last.parent == other | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment