# Read lines instructions = [] with open("8.input") as f: for line in f.readlines(): line = line.strip() (instr, arg) = line.split(" ") instructions.append((instr, int(arg.replace("+", "")))) def run(program): pc = 0 acc = 0 visited = set() while pc not in visited: try: (instr, arg) = program[pc] except IndexError: break if instr == "nop": pass elif instr == "acc": acc += arg elif instr == "jmp": pc += arg - 1 visited.add(pc) pc += 1 return (pc, acc) (_, acc) = run(instructions) print("Answer 1: " + str(acc)) for (i, (instr, arg)) in enumerate(instructions): if instr == "jmp" or instr == "nop": program = list(instructions) if instr == "nop": program[i] = ("jmp", arg) else: program[i] = ("nop", arg) (pc, acc) = run(program) if pc == len(program): print("Answer 2: " + str(acc))