Skip to content

Instantly share code, notes, and snippets.

@jonmcoe
Created March 5, 2021 17:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonmcoe/5a615a7a29993cc97b6cb9e3fd00561e to your computer and use it in GitHub Desktop.
Save jonmcoe/5a615a7a29993cc97b6cb9e3fd00561e to your computer and use it in GitHub Desktop.
i1 = ["B,E,F", "A,B,C,D", "D,G,I", "G,H"]
class Node:
def __init__(self, name):
self.name = name
self.children = set()
def __repr__(self): # just for debugging
return f"{self.name}: {self.children}"
def print(self, depth=0):
print("." * depth + self.name)
for c in sorted(self.children, key=lambda x: x.name):
c.print(depth=depth+1)
def create(l):
apices = {}
all_nodes = {}
for s in l:
x = s.split(',')
head = x[0]
tail = x[1:]
if head in all_nodes:
cur_node = all_nodes[head]
else:
cur_node = Node(head)
for element in tail:
if element in apices:
apices.pop(element)
if element in all_nodes:
cur_child = all_nodes[element]
else:
cur_child = Node(element)
cur_node.children.add(cur_child)
all_nodes[element] = cur_child
if head not in all_nodes:
apices[head] = cur_node
all_nodes[head] = cur_node
return list(apices.values())
for apex in create(i1):
apex.print()
"""
A
.B
..E
..F
.C
.D
..G
...H
..I
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment