70 lines
1.4 KiB
Python
70 lines
1.4 KiB
Python
from functools import reduce
|
|
def product(seq):
|
|
return reduce((lambda x,y: x*y), seq)
|
|
|
|
def maybeint(x):
|
|
if x.isdigit():
|
|
return int(x)
|
|
return x
|
|
|
|
def parse(input):
|
|
lines = []
|
|
for line in open(input):
|
|
lines.append(list(map(maybeint, line.split())))
|
|
return lines
|
|
|
|
def parse2(input):
|
|
lines = []
|
|
for line in open(input):
|
|
lines.append(line.rstrip("\n"))
|
|
return lines
|
|
|
|
def transpose(m):
|
|
out = []
|
|
xn = len(m[0])
|
|
for r in m:
|
|
assert len(r) == xn
|
|
for x in range(xn):
|
|
out.append([r[x] for r in m])
|
|
return out
|
|
|
|
def solve(input):
|
|
m = transpose(parse(input))
|
|
t = 0
|
|
for r in m:
|
|
r = list(r)
|
|
op = r.pop()
|
|
if op == "+":
|
|
t += sum(r)
|
|
if op == "*":
|
|
t += product(r)
|
|
print(t)
|
|
|
|
def solve2(input):
|
|
txt = parse2(input)
|
|
txt2 = transpose(txt)
|
|
stack = []
|
|
op = None
|
|
t = 0
|
|
for x in reversed(txt2):
|
|
line = "".join(x)
|
|
if line.endswith(("*", "+")):
|
|
op = line[-1]
|
|
line = line.strip(" \n*+")
|
|
if line == "":
|
|
continue
|
|
stack.append(int(line))
|
|
if op:
|
|
if op == "+":
|
|
t += sum(stack)
|
|
if op == "*":
|
|
t += product(stack)
|
|
stack.clear()
|
|
op = None
|
|
print(t)
|
|
|
|
solve("sample")
|
|
solve("input")
|
|
solve2("sample")
|
|
solve2("input")
|