-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday9.py
97 lines (85 loc) · 2.2 KB
/
day9.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
class Context(object):
def __init__(self):
self.level = 0
self.score = 0
self.inGarbage = False
self.skipping = False
self.garbage = 0
def ignoring(self):
return self.inGarbage or self.skipping
def curlyBegins(ctx):
if not ctx.ignoring():
ctx.level += 1
ctx.score += ctx.level
else:
if ctx.skipping:
ctx.skipping = False
else:
ctx.garbage += 1
def bang(ctx):
# ignore this ! if I am skipping, and turn off skipping
ctx.skipping = not ctx.skipping
def curlyEnds(ctx):
if not ctx.ignoring():
ctx.level -= 1
else:
if ctx.skipping:
ctx.skipping = False
else:
ctx.garbage += 1
def angleBegins(ctx):
if not ctx.ignoring():
ctx.inGarbage = True
else:
if ctx.skipping:
ctx.skipping = False
else:
ctx.garbage += 1
def angleEnds(ctx):
if not ctx.skipping:
if ctx.inGarbage:
ctx.inGarbage = False
else:
ctx.skipping = False
def process(file):
operations = {
'{' : curlyBegins,
'}' : curlyEnds,
'!' : bang,
'<' : angleBegins,
'>' : angleEnds,
}
context = Context()
nRead = 0
with open(file, "r") as f:
while True:
c = f.read(1)
if not c:
break
else:
nRead += 1
if context.level < 0:
print("Something went wrong")
processCharacter(c, operations, context)
return context.garbage
def processCharacter(c, operations, context):
if c in operations.keys():
operations[c](context)
elif context.skipping:
context.skipping = False
elif context.inGarbage:
context.garbage += 1
def testMe(characters):
operations = {
'{' : curlyBegins,
'}' : curlyEnds,
'!' : bang,
'<' : angleBegins,
'>' : angleEnds,
}
context = Context()
for eachCharacater in characters:
processCharacter(eachCharacater, operations, context)
return context.score
print(testMe("{{<{}!>,>{}}}"))
print(process("day9Input.txt"))