Advertisement
Guest User

Untitled

a guest
Dec 9th, 2019
377
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.61 KB | None | 0 0
  1. import sys
  2. import collections
  3. # usage pyhon3 9.1.py program input
  4.  
  5. def run(inp):
  6.     initmem = list(map(int, open(sys.argv[1]).read().split(',')))
  7.     mem = collections.defaultdict(lambda: 0, enumerate(initmem))
  8.     pc,base = 0, 0
  9.     while mem[pc] != 99:
  10.         opcode = mem[pc] % 100
  11.         modes = ("%05d" % mem[pc])[0:3]
  12.         o1 = base if modes[2] == '2' else 0
  13.         o2 = base if modes[1] == '2' else 0
  14.         o3 = base if modes[0] == '2' else 0
  15.         if opcode in (1,2,3,4,5,6,7,8,9):
  16.             op1 = mem[pc+1] if modes[2] == '1' else mem[o1+mem[pc+1]]
  17.         if opcode in (1,2,5,6,7,8):
  18.             op2 = mem[pc+2] if modes[1] == '1' else mem[o2+mem[pc+2]]
  19.         if opcode in (1,2): # add and mul
  20.             f = {1: int.__add__, 2: int.__mul__}[opcode]
  21.             mem[o3+mem[pc+3]] = f(op1,op2)
  22.             pc += 4
  23.         elif opcode == 3: # input
  24.             mem[o1+mem[pc+1]] = inp.pop(0)
  25.             pc += 2
  26.         elif opcode  == 4: # output
  27.             pc += 2
  28.             yield op1
  29.         elif opcode == 5: # jump if true
  30.             pc = op2 if op1 != 0 else pc+3
  31.         elif opcode == 6: # jump if false
  32.             pc = op2 if op1 == 0 else pc+3
  33.         elif opcode == 7: # less than
  34.             mem[o3+mem[pc+3]] = 1 if op1 < op2 else 0
  35.             pc += 4
  36.         elif opcode == 8: # equals
  37.             mem[o3+mem[pc+3]] = 1 if op1 == op2 else 0
  38.             pc += 4
  39.         elif opcode == 9: # set relative base
  40.             base += op1
  41.             pc += 2
  42.         else: raise Exception("invalid opcode %d" % opcode)
  43.  
  44. for out in run([int(sys.argv[2])]):
  45.     print(out)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement