python(day18): aaaaaaaaaaaAAAAAAAAAAAAAAAAAAAaaaaaaaaAAAAAAAAAAaaaaaAAAAaaaaaAAAAAAAAAAa
This commit is contained in:
parent
df67c9069c
commit
5bacc864b4
1 changed files with 52 additions and 0 deletions
52
python/day18.py
Normal file
52
python/day18.py
Normal file
|
@ -0,0 +1,52 @@
|
||||||
|
import fileinput
|
||||||
|
|
||||||
|
|
||||||
|
def solve(line):
|
||||||
|
if line[0].isdigit():
|
||||||
|
if len(line) == 1:
|
||||||
|
return int(line[0])
|
||||||
|
if len(line) == 3 and line[1] == '+':
|
||||||
|
return int(line[0]) + int(line[2])
|
||||||
|
if len(line) == 3 and line[1] == '*':
|
||||||
|
return int(line[0]) * int(line[2])
|
||||||
|
if line[1] == '+':
|
||||||
|
if line[2] == '(':
|
||||||
|
depth = 1
|
||||||
|
for i, c in enumerate(line[3:]):
|
||||||
|
if c == '(':
|
||||||
|
depth += 1
|
||||||
|
if c == ')':
|
||||||
|
depth -= 1
|
||||||
|
if depth == 0:
|
||||||
|
break
|
||||||
|
|
||||||
|
inner = int(line[0]) + solve(line[3:i+3])
|
||||||
|
return solve([str(inner)] + line[i+4:])
|
||||||
|
else:
|
||||||
|
v = solve(line[:3])
|
||||||
|
return solve([str(v)] + line[3:])
|
||||||
|
if line[1] == '*':
|
||||||
|
return solve(line[:1]) * solve(line[2:])
|
||||||
|
raise BaseException(f"HELP {repr(line)}")
|
||||||
|
|
||||||
|
|
||||||
|
if line[0] == '(':
|
||||||
|
depth = 1
|
||||||
|
for i, c in enumerate(line[1:]):
|
||||||
|
if c == '(':
|
||||||
|
depth += 1
|
||||||
|
if c == ')':
|
||||||
|
depth -= 1
|
||||||
|
if depth == 0:
|
||||||
|
break
|
||||||
|
|
||||||
|
inner = str(solve(line[1:i+1]))
|
||||||
|
return solve([inner] + line[i+2:])
|
||||||
|
|
||||||
|
summ = 0
|
||||||
|
for line in fileinput.input():
|
||||||
|
line = line.replace(" ", "").strip()
|
||||||
|
v = solve(list(line))
|
||||||
|
print(line, v)
|
||||||
|
summ += v
|
||||||
|
print(summ)
|
Loading…
Reference in a new issue