solution.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #!/usr/bin/python3
  2. import sys
  3. # part 1
  4. def add(a, b): return a + b
  5. def sub(a, b): return a - b
  6. def mul(a, b): return a * b
  7. def div(a, b): return a // b
  8. ops = { '+': add, '-': sub, '*': mul, '/': div, }
  9. def part1():
  10. monkeys = []
  11. leafs = {}
  12. for line in sys.stdin:
  13. monkey = line.split()
  14. if len(monkey) > 2:
  15. name, l, op, r = monkey
  16. monkeys.append((name.strip(':'), l, r, op))
  17. else:
  18. name, num = monkey
  19. leafs[name.strip(':')] = int(num)
  20. print(monkeys)
  21. print(leafs)
  22. while len(monkeys) > 0:
  23. for i in range(len(monkeys)):
  24. if monkeys[i][1] in leafs and monkeys[i][2] in leafs:
  25. name, l, r, op = monkeys.pop(i)
  26. leafs[name] = ops[op](leafs[l], leafs[r])
  27. break
  28. print(monkeys)
  29. print(leafs)
  30. def part2():
  31. orig_monkeys = []
  32. orig_leafs = {}
  33. for line in sys.stdin:
  34. monkey = line.split()
  35. if len(monkey) > 2:
  36. name, l, op, r = monkey
  37. orig_monkeys.append((name.strip(':'), l, r, op))
  38. else:
  39. name, num = monkey
  40. orig_leafs[name.strip(':')] = int(num)
  41. print(orig_monkeys)
  42. print(orig_leafs)
  43. solved = False
  44. # solution found through trying out humn seeds and manual intervention
  45. humn = 3353687996510
  46. while not solved:
  47. monkeys = orig_monkeys.copy()
  48. leafs = orig_leafs.copy()
  49. leafs['humn'] = humn
  50. while len(monkeys) > 0:
  51. for i in range(len(monkeys)):
  52. if monkeys[i][1] in leafs and monkeys[i][2] in leafs:
  53. name, l, r, op = monkeys.pop(i)
  54. leafs[name] = ops[op](leafs[l], leafs[r])
  55. if name == 'root':
  56. solved = leafs[l] == leafs[r]
  57. print(f'root with resolution {leafs[l]} == {leafs[r]} = {solved} (humn {humn})')
  58. if leafs[l] < leafs[r]: return
  59. break
  60. humn += 1
  61. #humn += 1000
  62. if sys.argv[1] in '1':
  63. part1()
  64. else:
  65. part2()