-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathtree-string-expression-balanced-parenthesis.py
More file actions
55 lines (42 loc) · 1.08 KB
/
tree-string-expression-balanced-parenthesis.py
File metadata and controls
55 lines (42 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
from collections import defaultdict
"""
Given a tree string expression in balanced parenthesis format:
(A(B(C)(D))(E)(F))
A
/ | \
B E F
/ \
C D
The function is to return the root of the tree you build, and if you can please
print the tree with indentations like above.
You can print in the simplified format.
A
B E F
C D
"""
def parse_string(s):
levels = defaultdict(list) # dict of lists
level_count = 0
for i, c in enumerate(s):
if c == '(':
level_count += 1
elif c == ')':
level_count -= 1
else:
levels[level_count].append(c)
return levels
def print_levels(levels):
for level in levels:
for c in levels[level]:
print c,
print
def main():
#tree = "(A(B(C))"
#tree = "(A(B(C)D)"
tree = "(A(B(C)(D))(E)(F))"
levels = parse_string(tree)
# TODO make sure that levels are accesed in order
# sort the dict into a list
print_levels(levels)
if __name__ == "__main__":
main()