import copy with open("data.txt", "r", encoding="utf-8") as f: prg = [x.rstrip().split(" ") for x in f] def run(prg): acc = 0 used_insts = set() i = 0 l = len(prg) while i not in used_insts and i < l: used_insts.add(i) inst, val = prg[i] if inst == "nop": pass elif inst == "acc": acc += int(val) elif inst == "jmp": i += int(val) continue i += 1 return acc, i >= l # Part 1 acc, _ = run(prg) print(f"1: Accumulator is {acc}.") # Part 2 ok = False i = 0 while not ok: aprg = copy.deepcopy(prg) for j in range(i, len(aprg) - 1): if aprg[j][0] == "nop": aprg[j][0] = "jmp" break elif aprg[j][0] == "jmp": aprg[j][0] = "nop" break acc, ok = run(aprg) i += 1 assert i <= len(aprg) print(f"2: Accumulator is {acc}.")