61 lines
1.2 KiB
Python
61 lines
1.2 KiB
Python
from lib import get_data
|
|
from typing import TypeVar
|
|
|
|
T = TypeVar('T')
|
|
|
|
data = """123 328 51 64
|
|
45 64 387 23
|
|
6 98 215 314
|
|
* + * + """
|
|
data = get_data(__file__)
|
|
|
|
def mul(xs):
|
|
r = 1
|
|
for x in xs:
|
|
r *= x
|
|
return r
|
|
|
|
lines = zip(*[line.split() for line in data.splitlines()])
|
|
|
|
r = 0
|
|
for xs in lines:
|
|
xs, op = xs[:-1], xs[-1]
|
|
xs = list(map(int, xs))
|
|
if op == "+":
|
|
r += sum(xs)
|
|
elif op == "*":
|
|
r += mul(xs)
|
|
else:
|
|
assert False, "Unexpected op"
|
|
print(r)
|
|
|
|
def split(xs: list[T], delim: T) -> list[list[T]]:
|
|
res = [[]]
|
|
for x in xs:
|
|
if x == delim:
|
|
res.append([])
|
|
else:
|
|
res[-1].append(x)
|
|
return res
|
|
|
|
chars_trans: list[tuple[str]] = list(zip(*[line for line in data.splitlines()]))
|
|
lines_trans: list[str] = list(map(lambda line: "".join(line).strip(), chars_trans))
|
|
cols: list[list[str]] = split(lines_trans, '')
|
|
|
|
r2 = 0
|
|
for xs in cols:
|
|
x0 = xs[0]
|
|
acc, op = int(x0[:-1]), x0[-1]
|
|
for x in xs[1:]:
|
|
x = int(x)
|
|
if op == "+":
|
|
acc += x
|
|
elif op == "*":
|
|
acc *= x
|
|
else:
|
|
assert False, "Unexpected op"
|
|
r2 += acc
|
|
|
|
print(r2)
|
|
|