forked from ngiengkianyew/daily-coding-problem
-
Notifications
You must be signed in to change notification settings - Fork 1
/
problem_344.py
50 lines (40 loc) · 919 Bytes
/
problem_344.py
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
class Node:
def __init__(self, val):
self.val = val
self.ch = set()
self.par = None
def size(self):
if not self.ch:
return 1
return 1 + sum([x.size() for x in self.ch])
def split(node):
results = list()
for child in node.ch:
if child.size() % 2 == 0:
new_children = [x for x in node.ch if x != child]
node.ch = new_children
return [node, child]
else:
results.extend(split(child))
return results
def segment(nodes):
new_nodes = list()
count = len(nodes)
for node in nodes:
new_nodes = split(node)
if len(new_nodes) == count:
return count
return segment(new_nodes)
# Tests
a = Node(1)
b = Node(2)
c = Node(3)
d = Node(4)
e = Node(5)
f = Node(6)
g = Node(7)
h = Node(8)
d.ch = [f, g, h]
c.ch = [d, e]
a.ch = [b, c]
assert segment([a]) == 2