126 lines
3.2 KiB
Python
126 lines
3.2 KiB
Python
from aoc.input import get_input
|
|
import copy
|
|
import itertools
|
|
import time
|
|
import collections
|
|
import re
|
|
from aoc.partselector import part_one, part_two
|
|
import functools
|
|
|
|
def pw(line):
|
|
return line.strip()
|
|
|
|
def p1():
|
|
inp = get_input(pw)
|
|
tot = []
|
|
for sample in inp:
|
|
stack = []
|
|
operand = ''
|
|
operator = ''
|
|
for i in sample[0:]:
|
|
if i == ' ':
|
|
continue
|
|
if i in list(map(str, range(10))):
|
|
operand = i
|
|
if operator == '':
|
|
res = int(operand)
|
|
elif operator == '+':
|
|
res += int(operand)
|
|
elif operator == '*':
|
|
res *= int(operand)
|
|
if i == '(':
|
|
stack.append((res, operator))
|
|
operator = ''
|
|
res = 0
|
|
elif i == ')':
|
|
value, operator = stack.pop()
|
|
if operator == '':
|
|
res = value
|
|
elif operator == '+':
|
|
res += value
|
|
elif operator == '*':
|
|
res *= value
|
|
else:
|
|
operator = i
|
|
tot.append(res)
|
|
res = 0
|
|
|
|
print(sum(tot))
|
|
return inp
|
|
|
|
|
|
def p2():
|
|
inp = get_input(pw)
|
|
rr = []
|
|
for sample in inp:
|
|
stack = []
|
|
operand = ''
|
|
operator = ''
|
|
#print(sample)
|
|
for i in sample[0:]:
|
|
if i == ' ':
|
|
continue
|
|
if i in list(map(str, range(10))):
|
|
operand = i
|
|
if operator == '':
|
|
res = int(operand)
|
|
elif operator == '+':
|
|
res += int(operand)
|
|
elif operator == '*':
|
|
res *= int(operand)
|
|
if i == '(':
|
|
stack.append((res, operator, '('))
|
|
operator = ''
|
|
res = 0
|
|
elif i == ')':
|
|
brace = ''
|
|
while brace != '(':
|
|
value, operator, brace = stack.pop()
|
|
if operator == '':
|
|
if value != 0:
|
|
res = value
|
|
elif operator == '+':
|
|
res += value
|
|
elif operator == '*':
|
|
res *= value
|
|
else:
|
|
operator = i
|
|
if operator == '*':
|
|
stack.append((res, operator, ''))
|
|
operator = ''
|
|
res = 0
|
|
#print(i, res, stack)
|
|
while(len(stack)>0):
|
|
#print(res, stack)
|
|
value, operator, brace = stack.pop()
|
|
if operator == '':
|
|
if value != 0:
|
|
res = value
|
|
elif operator == '+':
|
|
res += value
|
|
elif operator == '*':
|
|
res *= value
|
|
|
|
|
|
#print(res)
|
|
rr.append(res)
|
|
res = 0
|
|
|
|
print(sum(rr))
|
|
|
|
return 0
|
|
|
|
result1 = None
|
|
if part_one():
|
|
start = time.time()
|
|
result1 = p1()
|
|
print(round(1000*(time.time() - start), 2), 'ms')
|
|
|
|
|
|
if part_two():
|
|
start = time.time()
|
|
p2()
|
|
print(round(1000*(time.time() - start), 2), 'ms')
|
|
|
|
|