8.py 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. # Read lines
  2. instructions = []
  3. with open("8.input") as f:
  4. for line in f.readlines():
  5. line = line.strip()
  6. (instr, arg) = line.split(" ")
  7. instructions.append((instr, int(arg.replace("+", ""))))
  8. def run(program):
  9. pc = 0
  10. acc = 0
  11. visited = set()
  12. while pc not in visited:
  13. try:
  14. (instr, arg) = program[pc]
  15. except IndexError:
  16. break
  17. if instr == "nop":
  18. pass
  19. elif instr == "acc":
  20. acc += arg
  21. elif instr == "jmp":
  22. pc += arg - 1
  23. visited.add(pc)
  24. pc += 1
  25. return (pc, acc)
  26. (_, acc) = run(instructions)
  27. print("Answer 1: " + str(acc))
  28. for (i, (instr, arg)) in enumerate(instructions):
  29. if instr == "jmp" or instr == "nop":
  30. program = list(instructions)
  31. if instr == "nop":
  32. program[i] = ("jmp", arg)
  33. else:
  34. program[i] = ("nop", arg)
  35. (pc, acc) = run(program)
  36. if pc == len(program):
  37. print("Answer 2: " + str(acc))