-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday8.py
53 lines (45 loc) · 1.9 KB
/
day8.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
import re
from collections import defaultdict
class RegisterProcessor(object):
def __init__(self, instructions):
self.registers = defaultdict(int)
self.instructions = self.parse_instructions(instructions)
self.current_highest = 0
for i in self.instructions:
self.handle_instruction(i)
def parse_instructions(self, instructions):
out = []
instructions = instructions.strip().split('\n')
instructions = [i.strip() for i in instructions]
for line in instructions:
rgx = re.compile('^(\w+) (inc|dec) (-?\d+) if (\w+) (.*) (-?\d+)$')
matches = rgx.search(line)
out.append(matches.groups())
return out
def handle_instruction(self, instruction):
target = instruction[0]
operation = instruction[1]
num = instruction[2]
eval_target = instruction[3]
eval_comparator = instruction[4]
eval_against = instruction[5]
if eval('self.registers["%s"] %s %s' % (eval_target,
eval_comparator,
eval_against)):
if operation == 'inc':
self.registers[target] += int(num)
elif operation == 'dec':
self.registers[target] -= int(num)
if self.registers[target] > self.current_highest:
self.current_highest = self.registers[target]
@property
def highest_value(self):
max_int = [{k: v} for k, v in self.registers.items()
if v == max(self.registers.values())]
return max_int[0]
if __name__ == '__main__': # pragma: no cover
with open('day8_input.txt') as f:
data = f.read()
rp = RegisterProcessor(data)
print('Highest value found in any register:', rp.highest_value)
print('Highest value ever reached during processing:', rp.current_highest)