51 lines
1.5 KiB
Python
51 lines
1.5 KiB
Python
|
#!/bin/python3
|
||
|
import sys,re
|
||
|
from pprint import pprint
|
||
|
sys.path.insert(0, '../../')
|
||
|
from fred import list2int,get_re,nprint,lprint
|
||
|
|
||
|
input_f = 'input'
|
||
|
|
||
|
part = 2
|
||
|
#########################################
|
||
|
# #
|
||
|
# Part 1 #
|
||
|
# #
|
||
|
#########################################
|
||
|
result = 0
|
||
|
if part == 1:
|
||
|
with open(input_f) as file:
|
||
|
for line in file:
|
||
|
for i in re.findall(r"(mul\((\d+),{1}(\d+)\))",line.rstrip()):
|
||
|
result += (int(i[1])*int(i[2]))
|
||
|
|
||
|
print(result)
|
||
|
|
||
|
|
||
|
|
||
|
#########################################
|
||
|
# #
|
||
|
# Part 2 #
|
||
|
# #
|
||
|
#########################################
|
||
|
result = 0
|
||
|
do = True
|
||
|
if part == 2:
|
||
|
with open(input_f) as file:
|
||
|
for line in file:
|
||
|
matches = re.findall(r"mul\(\d+,\d+\)|do\(\)|don't\(\)",line.rstrip())
|
||
|
for match in matches:
|
||
|
if match == 'do()':
|
||
|
do = True
|
||
|
elif match == "don't()":
|
||
|
do = False
|
||
|
else:
|
||
|
if do:
|
||
|
m = get_re(r"mul\((\d+),{1}(\d+)\)",match)
|
||
|
result += (int(m.group(1))*int(m.group(2)))
|
||
|
print(result)
|
||
|
|
||
|
# Not really happy with my code. I would prefer to find all mul(x,y) between do() and don't(),
|
||
|
# instead of finding all the mul/do/don't and then turning calculation on/off.
|
||
|
|
||
|
#(do\(\).*?mul\((\d+),{1}(\d+)\))
|