05_diag.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. #!/usr/bin/env python3
  2. import sys
  3. def run(p, inputs):
  4. pc = 0
  5. while p[pc] != 99:
  6. modes, opcode = divmod(p[pc], 100)
  7. def modeswitch(offset):
  8. value = p[pc + offset]
  9. mode = modes // (10 ** (offset - 1)) % 10
  10. return value if mode else p[value]
  11. if opcode in (1, 2):
  12. a = modeswitch(1)
  13. b = modeswitch(2)
  14. out = p[pc + 3]
  15. p[out] = a + b if opcode == 1 else a * b
  16. pc += 4
  17. elif opcode == 3:
  18. address = p[pc + 1]
  19. p[address] = inputs.pop()
  20. pc += 2
  21. elif opcode == 4:
  22. yield modeswitch(1)
  23. pc += 2
  24. elif opcode == 5:
  25. pc = modeswitch(2) if modeswitch(1) else pc + 3
  26. elif opcode == 6:
  27. pc = modeswitch(2) if not modeswitch(1) else pc + 3
  28. elif opcode in (7, 8):
  29. a = modeswitch(1)
  30. b = modeswitch(2)
  31. out = p[pc + 3]
  32. p[out] = int(a < b if opcode == 7 else a == b)
  33. pc += 4
  34. def initrun(p, inp):
  35. return list(run(list(p), list(inp)))
  36. program = list(map(int, sys.stdin.read().split(',')))
  37. print(initrun(program, [1])[-1])
  38. print(initrun(program, [5])[-1])