Solution to problem 18 part 2 in Python

This commit is contained in:
David Doblas Jiménez 2022-01-10 18:53:27 +01:00
parent 884fcca61f
commit 5a4a15fa2c

View File

@ -98,5 +98,91 @@ def part_1() -> None:
print(f"The result of evaluating my homework is {total}")
# --- Part Two ---
# You manage to answer the child's questions and they finish part 1 of their
# homework, but get stuck when they reach the next section: advanced math.
# Now, addition and multiplication have different precedence levels, but
# they're not the ones you're familiar with. Instead, addition is evaluated
# before multiplication.
# For example, the steps to evaluate the expression 1 + 2 * 3 + 4 * 5 + 6 are
# now as follows:
# 1 + 2 * 3 + 4 * 5 + 6
# 3 * 3 + 4 * 5 + 6
# 3 * 7 * 5 + 6
# 3 * 7 * 11
# 21 * 11
# 231
# Here are the other examples from above:
# 1 + (2 * 3) + (4 * (5 + 6)) still becomes 51.
# 2 * 3 + (4 * 5) becomes 46.
# 5 + (8 * 3 + 9 + 3 * 4 * 3) becomes 1445.
# 5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4)) becomes 669060.
# ((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2 becomes 23340.
# What do you get if you add up the results of evaluating the homework problems
# using these new rules?
def simplify_rules(expr) -> str:
while len(expr) > 1:
ordered_stack, hold = [], []
done = False
while not done and len(expr) > 0:
char = expr.pop()
if char == "+":
done = True
hold.append(char)
if not done and len(expr) == 0:
result = simplify(hold)
expr.append(result)
else:
ordered_stack.append(expr.pop())
for _ in range(2):
ordered_stack.append(hold.pop())
result = simplify(ordered_stack)
hold.append(result)
while len(hold) > 0:
expr.append(hold.pop())
return expr[0]
def part_2() -> None:
total = 0
for line in homework:
line = line.replace("(", "( ")
line = line.replace(")", " )")
expr = line.split()
stack = []
for char in expr:
if char.isdigit() or char in ["+", "*", "("]:
stack.append(char)
elif char == ")":
ordered_stack = []
while stack[len(stack) - 1] != "(":
ordered_stack.append(stack.pop())
stack.pop()
result = simplify_rules(ordered_stack)
stack.append(result)
stack.reverse()
result = simplify_rules(stack)
total += int(result)
print(f"The result of evaluating my homework is {total}")
if __name__ == "__main__":
part_1()
part_2()