Skip to content

Instantly share code, notes, and snippets.

@ahvahsky2008
Last active August 12, 2021 13:46
Show Gist options
  • Save ahvahsky2008/ba564b723103b84a89dd01219423cb2a to your computer and use it in GitHub Desktop.
Save ahvahsky2008/ba564b723103b84a89dd01219423cb2a to your computer and use it in GitHub Desktop.
class Node:
def __init__(self, name: str, parent: 'Node' = None):
self.name = name
self.parent = parent
self.children = []
def add_child(self, obj: 'Node'):
self.children.append(obj)
@property
def parent_name(self) -> str:
return self.parent.name if self.parent else None
def __repr__(self) -> str:
return f'Node(name={self.name!r}, parent={self.parent_name!r}, children_len={len(self.children)})'
def to_dict(self) -> dict:
def _to_dict(node: Node):
return {child.name: _to_dict(child) for child in node.children}
return _to_dict(self)
source = [
(None, 'a'),
(None, 'b'),
(None, 'c'),
('a', 'a1'),
('a', 'a2'),
('a2', 'a21'),
('a2', 'a22'),
('b', 'b1'),
('b1', 'b11'),
('b11', 'b111'),
('b', 'b2'),
('c', 'c1'),
]
expected = {
'a': {'a1': {}, 'a2': {'a21': {}, 'a22': {}}},
'b': {'b1': {'b11': {'b111': {}}}, 'b2': {}},
'c': {'c1': {}},
}
def to_tree(source):
name_by_node = dict()
name_by_node[None] = Node('ROOT', None)
for parent, child in source:
parent_node = name_by_node[parent]
if child not in name_by_node:
name_by_node[child] = Node(child, parent_node)
parent_node.add_child(name_by_node[child])
return name_by_node[None].to_dict()
assert to_tree(source) == expected
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment