Created
January 1, 2021 19:38
-
-
Save joshbduncan/791893b389c0af4e4821f4fbd1b1da85 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def calc1(line): | |
nums = [int(x) for x in line if x not in ['+', '*']] | |
ops = [x for x in line if x in ['+', '*']] | |
total = nums.pop(0) | |
for n in nums: | |
if ops == []: | |
break | |
else: | |
total = eval(str(total) + ops.pop(0) + str(n)) | |
return total | |
def calc2(line): | |
while '+' in line: | |
for i, j in enumerate(line): | |
if j == '+': | |
total = int(line[i - 1]) + int(line[i + 1]) | |
line = line[:i - 1] + [total] + line[i + 2:] | |
break | |
return eval(''.join([str(x) for x in line])) | |
data = open("day18.in").read().strip().split('\n') | |
# part 1 | |
p1 = 0 | |
for line in data: | |
line = line.replace('(', '( ').replace(')', ' )').split(' ') | |
while '(' in line: | |
start = 0 | |
end = 0 | |
for i, j in enumerate(line): | |
if j == '(': | |
start = i | |
if j == ')': | |
end = i | |
total = calc1(line[start + 1:end]) | |
line = line[:start] + [total] + line[end + 1:] | |
break | |
p1 += calc1(line) | |
print(f'Part 1: {p1}') | |
# part 2 | |
p2 = 0 | |
for line in data: | |
line = line.replace('(', '( ').replace(')', ' )').split(' ') | |
while '(' in line: | |
start = 0 | |
end = 0 | |
for i, j in enumerate(line): | |
if j == '(': | |
start = i | |
if j == ')': | |
end = i | |
total = calc2(line[start + 1:end]) | |
line = line[:start] + [total] + line[end + 1:] | |
break | |
p2 += calc2(line) | |
print(f'Part 2: {p2}') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment