-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpuzzle7_2.py
82 lines (69 loc) · 1.96 KB
/
puzzle7_2.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import numpy as np
import sys
with open('day7.in','r') as infile:
lines = infile.readlines()
colors = {}
for line in lines:
col = line.split('bags')[0].strip()
contain = line.split('contain')[1].strip()[:-1].split(', ')
subcols = []
for c in contain:
if not c.startswith('no other'):
subcols.append(c.split('bag')[0].strip())
else:
subcols.append(c.split('bag')[0].strip())
colors.update({col:subcols})
#print(colors)
tree_end = []
for key in colors:
if colors[key] == ['no other']:
tree_end.append(key)
print("End of tree bags:",tree_end)
def walk_tree(tree,parent_node,parent_nr,parent_pos,val_dict):
""" leste litt på på wiki om binære trær og ikke binære
Pre-order (NLR)
1. Perform pre-order operation.
2. For each i from 1 to the number of children do:
Visit i-th, if present.
Perform in-order operation.
3. Perform post-order operation.
preorder(node)
if (node == null)
return
visit(node)
preorder(node.left)
preorder(node.right)
"""
if parent_node in tree_end:
pos = parent_pos
return pos,val_dict
N_nodes = len(tree[parent_node])
children = tree[parent_node]
for i in range(N_nodes):
child = children[i][2:]
child_nr = int(children[i][:2])
pos = parent_pos + str(i)
val_dict.update({pos:child_nr})
print(child,":",child_nr,"--> position:",pos)
pos,val_dict = walk_tree(tree,child,child_nr,pos,val_dict)
return pos,val_dict
color = 'shiny gold'
print("*START*\n", color)
val_dict = {}
pos,val_dict = walk_tree(colors,color,1,'',val_dict)
print("----")
print(val_dict)
print("----")
counter = 0
for key in val_dict:
if len(key) > 1:
c = val_dict[key[:len(key)+1]]
for i in range(1,len(key)):
c = c*val_dict[key[:i]]
#print("(c=",c,"val=",val_dict[key[:i]],"pos=",key[:i],")")
counter += c
#print("counter=",counter,"val=",val_dict[key],"pos=",key)
else:
counter += val_dict[key]
#print("counter=",counter,"val=",val_dict[key],"pos=",key,"(here)")
print(counter)