Advertisement
Guest User

Untitled

a guest
Dec 5th, 2019
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.47 KB | None | 0 0
  1. with open('in.txt', 'r') as f:
  2. data = [int(y) for x in f.readlines() for y in x.strip().split(',')]
  3.  
  4. iptr, code = 0, data[:]
  5. add, mul, inp, out, hlt = 1, 2, 3, 4, 99
  6. pos, imm = 0, 1
  7.  
  8. def get_input():
  9. return 1
  10.  
  11. def next():
  12. global code, iptr
  13. val, iptr = code[iptr], iptr + 1
  14. return val
  15.  
  16. def process_opcode(op):
  17. c = str(op)
  18. # If the opcode is a number 2 or less we can assume all modes are 0
  19. if len(c) <= 2:
  20. return int(c[-2:]), [0,0,0]
  21. # take the 3 first numbers and make a list then revese it
  22. return int(c[-2:]), ([0] * (5 - len(c)) + [int(x) for x in c])[:3][::-1]
  23.  
  24. def peek(val, mode):
  25. global code
  26. return mode == imm and val or code[val]
  27.  
  28. def poke(addr, val):
  29. global code
  30. code[addr] = val
  31.  
  32. outs = []
  33. while True:
  34. op, modes = process_opcode(next())
  35. # We can handle these better
  36. if op == add or op == mul:
  37. lval = peek(next(), modes[0])
  38. rval = peek(next(), modes[1])
  39. if op == add:
  40. poke(next(), lval + rval)
  41. elif op == mul:
  42. poke(next(), lval * rval)
  43. else:
  44. if op == inp:
  45. # input always writes to an address
  46. poke(next(), get_input())
  47. elif op == out:
  48. outs.append(peek(next(), pos))
  49. elif op == hlt:
  50. print(outs)
  51. print("Exiting program.")
  52. break
  53. else:
  54. print("Unexpected operation. Aborting.")
  55. break
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement