import copy def part1(): file = open("input.txt") instructions = [] for line in file: args = line.strip().split(" ") instructions.append({ 'op': args[0], 'arg': int(args[1]), 'visited': False }) finger = 0 acc = 0 while not instructions[finger]['visited']: op = instructions[finger]['op'] arg = instructions[finger]['arg'] instructions[finger]['visited'] = True if op == 'nop': finger += 1 continue elif op == 'jmp': finger += arg elif op == 'acc': acc += arg finger += 1 print("Part 1: %d" % acc) def brute(i, instructions): op = instructions[i]['op'] if op == 'nop': instructions[i]['op'] = 'jmp' elif op == 'jmp': instructions[i]['op'] = 'nop' else: return 0 finger = 0 acc = 0 while not instructions[finger]['visited']: op = instructions[finger]['op'] arg = instructions[finger]['arg'] instructions[finger]['visited'] = True if op == 'nop': finger += 1 continue elif op == 'jmp': finger += arg elif op == 'acc': acc += arg finger += 1 if instructions[len(instructions) - 1]['visited']: return acc return 0 def part2(): file = open("input.txt") instructions = [] for line in file: args = line.strip().split(" ") instructions.append({ 'op': args[0], 'arg': int(args[1]), 'visited': False }) acc = 0 for i in range(0, len(instructions)): op = instructions[i]['op'] if op == 'jmp' or op == 'nop': acc = brute(i, copy.deepcopy(instructions)) if acc > 0: break print("Part 2: %d" % acc) if __name__ == "__main__": part1() part2()