12_assembunny.py 1021 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. #!/usr/bin/env python3
  2. import sys
  3. def read_program(f):
  4. maybe_int = lambda x: int(x) if x.isdigit() or x[0] == '-' else x
  5. for line in f:
  6. yield tuple(map(maybe_int, line.split()))
  7. def run(p, init):
  8. regs = [0, 0, init, 0]
  9. pc = 0
  10. def load(x):
  11. return x if isinstance(x, int) else regs[ord(x) - ord('a')]
  12. def store(reg, value):
  13. regs[ord(reg) - ord('a')] = value
  14. while pc < len(p):
  15. instr = p[pc]
  16. opcode = instr[0]
  17. if opcode == 'cpy':
  18. src, dst = instr[1:]
  19. store(dst, load(src))
  20. elif opcode == 'inc':
  21. reg = instr[1]
  22. store(reg, load(reg) + 1)
  23. elif opcode == 'dec':
  24. reg = instr[1]
  25. store(reg, load(reg) - 1)
  26. elif opcode == 'jnz':
  27. pred, offset = instr[1:]
  28. if load(pred):
  29. pc += load(offset) - 1
  30. pc += 1
  31. return regs[0]
  32. program = list(read_program(sys.stdin))
  33. print(run(program, 0))
  34. print(run(program, 1))