Skip to content

Instantly share code, notes, and snippets.

@freedomofkeima
Last active December 8, 2021 09:01
Show Gist options
  • Save freedomofkeima/10edc102d26570d9e9b22925d63b224b to your computer and use it in GitHub Desktop.
Save freedomofkeima/10edc102d26570d9e9b22925d63b224b to your computer and use it in GitHub Desktop.
Advent of Code 2020
result = 0
def new_calculate(line):
if '+' not in line and '*' not in line:
return int(line)
flatten = ""
idx = 0
ctx = 0
temp = ""
while len(line) > idx:
if line[idx] == '(':
if ctx != 0:
temp += '('
ctx += 1
elif line[idx] == ')':
ctx -= 1
if ctx == 0:
flatten += str(new_calculate(temp))
temp = ""
else:
temp += ')'
else:
if ctx == 0:
flatten += line[idx]
else:
temp += line[idx]
idx += 1
for c in ('*', '+'):
left, operator, right = flatten.partition(c)
if operator == '+':
return new_calculate(left) + new_calculate(right)
elif operator == '*':
return new_calculate(left) * new_calculate(right)
with open('18_input.txt') as f:
while True:
line = f.readline()
if not line or line.rstrip() == "":
if not line:
break
continue
line = line.rstrip()
print(line)
temp = new_calculate(line)
print(temp)
result += temp
print(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment