18.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. lines = []
  2. with open("18.input") as f:
  3. for line in f.readlines():
  4. lines.append(line.strip())
  5. def parse(line):
  6. res = []
  7. i = 0
  8. while i < len(line):
  9. c = line[i]
  10. i += 1
  11. if c in "0123456789+*":
  12. res.append(c)
  13. elif c == '(':
  14. buf = []
  15. depth = 1
  16. while True:
  17. c = line[i]
  18. i += 1
  19. if c == '(':
  20. depth += 1
  21. elif c == ')':
  22. depth -= 1
  23. if depth == 0:
  24. break
  25. buf.append(c)
  26. res.append(parse(buf))
  27. return res
  28. def task_1(expression):
  29. res = int(expression[0])
  30. i = 1
  31. while i < len(expression):
  32. op = expression[i]
  33. i += 1
  34. val = int(expression[i])
  35. i += 1
  36. if op == '*':
  37. res *= val
  38. elif op == '+':
  39. res += val
  40. return res
  41. def task_2(expression):
  42. # evaluate additions
  43. i = 0
  44. while i < len(expression):
  45. if expression[i] == '+':
  46. expression[i - 1] = int(expression[i - 1]) + int(expression[i + 1])
  47. del expression[i:i+2]
  48. i = i - 1
  49. i += 1
  50. # evaluate multiplications
  51. i = 0
  52. while i < len(expression):
  53. if expression[i] == '*':
  54. expression[i - 1] = int(expression[i - 1]) * int(expression[i + 1])
  55. del expression[i:i+2]
  56. i = i - 1
  57. i += 1
  58. assert len(expression) == 1
  59. return expression[0]
  60. def evaluate(expression, presedence_function):
  61. if len(expression) == 1:
  62. try:
  63. return int(expression[0])
  64. except ValueError:
  65. return evaluate(expression[0], presedence_function)
  66. else:
  67. expression = [e if type(e) is not list else evaluate(e, presedence_function) for e in expression]
  68. # now we no parentheses left :-)
  69. return presedence_function(expression)
  70. print("Answer 1:", sum([evaluate(parse(line), task_1) for line in lines]))
  71. print("Answer 2:", sum([evaluate(parse(line), task_2) for line in lines]))