0

Im doing day 8 in the AdventofCode calendar, and in it there is a mock bootup sequence that has an error in it. there are three types of instructions, acc, jmp and nop, and to make the sequence boot, ONE of the jmp's have to be raplaced by a nop. I wrote this code:

def fixError(o_list):
    jmpPositions = []
    for jmp in range(len(o_list)):                  # finds all positions where there is a jump
        if o_list[jmp][0] == 'jmp':
            jmpPositions.append(jmp)
    print(jmpPositions)


    for j in jmpPositions:
        global accumulator
        accumulator = 0

        n_list = list(o_list)
        print('\nBefore correction',n_list)
        print('replacing at', j)
        n_list[j][0] = 'nop'
        print('After correction ',n_list)

fixError(instructions)

However, it seems like the code doesn't make n_list (new list) a copy of o_list (original list)

[2, 4, 7]

Before correction [['nop', 0], ['acc', 1], ['jmp', 4], ['acc', 3], ['jmp', -3], ['acc', -99], ['acc', 1], ['jmp', -4], ['acc', 6]]
replacing at 2
After correction  [['nop', 0], ['acc', 1], ['nop', 4], ['acc', 3], ['jmp', -3], ['acc', -99], ['acc', 1], ['jmp', -4], ['acc', 6]]


Before correction [['nop', 0], ['acc', 1], ['nop', 4], ['acc', 3], ['jmp', -3], ['acc', -99], ['acc', 1], ['jmp', -4], ['acc', 6]]
replacing at 4
After correction  [['nop', 0], ['acc', 1], ['nop', 4], ['acc', 3], ['nop', -3], ['acc', -99], ['acc', 1], ['jmp', -4], ['acc', 6]]


Before correction [['nop', 0], ['acc', 1], ['nop', 4], ['acc', 3], ['nop', -3], ['acc', -99], ['acc', 1], ['jmp', -4], ['acc', 6]]
replacing at 7
After correction  [['nop', 0], ['acc', 1], ['nop', 4], ['acc', 3], ['nop', -3], ['acc', -99], ['acc', 1], ['nop', -4], ['acc', 6]]


As you can see, the previous correction-attempt remains in the next. As i said, you are only supposed to replace one of them. I have tried all sorts of methods for creating a proper copy, like

new_list = old_list.copy()
new_list = old_list[:]
new_list = list(old_list)
new_list = copy.copy(old_list)
etc...

What am i doing wrong ?

Iscariot
  • 11
  • 5

1 Answers1

0

you are trying shallow copy which will not work if you have list inside a list.

you can try deepcopy.

import copy
new_list  = copy.deepcopy(old_list)
Amit Kumar
  • 613
  • 3
  • 15