I'm trying to write a little bit of code to complete an exercise on codewars link
Part of what I want to do is loop through a list of lists that are representing the sudoku grid and replace 0's with a list of possible numbers.
My problem is that even when I use list.copy() to hold the original puzzle any changes I make to the original list (not the copy) still changes the copy.
How can this be happening?
Below is my code:
def sudoku(puzzle):
# copy the puzzle to be able to save original positions that are changeable
pc = puzzle.copy()
puzzle = pns(puzzle)
return puzzle
def pns(puzzle):
for y in range(len(puzzle)):
for x in range(len(puzzle[0])):
pn = set(range(1,len(puzzle) + 1))
for row_idx in range(len(puzzle)):
for col_idx in range(len(puzzle[row_idx])):
skip_bool = True
if puzzle[y][x] != 0 and type(puzzle[y][x]) == type(1):
skip_bool = False
if row_idx == y and col_idx != x and type(puzzle[row_idx][col_idx]) != type([0]):
if puzzle[row_idx][col_idx] in pn:
pn.remove(puzzle[row_idx][col_idx])
if col_idx == x and row_idx != y and type(puzzle[row_idx][col_idx]) != type([0]):
if puzzle[row_idx][col_idx] in pn:
pn.remove(puzzle[row_idx][col_idx])
pn = list(pn)
if len(pn) == 1:
puzzle[y][x] = pn[0]
elif len(pn) == 0:
puzzle[y][x] = False
elif skip_bool:
puzzle[y][x] = pn
return puzzle
Expected output from:
print(pc)
print(puzzle)
[5, 3, 0, 0, 7, 0, 0, 0, 0]
[6, 0, 0, 1, 9, 5, 0, 0, 0]
[0, 9, 8, 0, 0, 0, 0, 6, 0]
[8, 0, 0, 0, 6, 0, 0, 0, 3]
[4, 0, 0, 8, 0, 3, 0, 0, 1]
[7, 0, 0, 0, 2, 0, 0, 0, 6]
[0, 6, 0, 0, 0, 0, 2, 8, 0]
[0, 0, 0, 4, 1, 9, 0, 0, 5]
[0, 0, 0, 0, 8, 0, 0, 7, 9]
[5, 3, [1, 2, 4, 6, 9], [2, 6, 9], 7, [1, 2, 4, 6, 8], [1, 4, 6, 8, 9], [1, 2, 4, 9], [2, 4, 8]]
[6, [2, 4, 7, 8], [2, 3, 4, 7], 1, 9, 5, [3, 4, 7, 8], [2, 3, 4], [2, 4, 7, 8]]
[[1, 2, 3], 9, 8, [2, 3, 5, 7], [3, 4, 5], [1, 2, 4, 7], [1, 3, 4, 5, 7], 6, [2, 4, 7]]
[8, [1, 2, 4, 5, 7], [1, 2, 4, 5, 7, 9], [2, 5, 7, 9], 6, [1, 2, 4, 7], [1, 4, 5, 7, 9], [1, 2, 4, 5, 9], 3]
[4, [2, 5, 7], [2, 5, 6, 7, 9], 8, 5, 3, [6, 7, 9], [2, 9], 1]
[7, [1, 4, 5, 8], [1, 3, 4, 5, 9], [3, 5, 9], 2, [1, 4, 8], [1, 3, 4, 5, 8, 9], [1, 3, 4, 5, 9], 6]
[[1, 3, 9], 6, [1, 3, 4, 5, 7, 9], [3, 5, 7, 9], [3, 4], [1, 4, 7], 2, 8, [4, 7]]
[[2, 3], [2, 7, 8], [2, 3, 6, 7], 4, 1, 9, [3, 6, 7, 8], [2, 3], 5]
[[1, 2, 3], [1, 2, 4, 5], [1, 2, 3, 4, 5, 6], [2, 3, 5, 6], 8, [1, 2, 4, 6], [1, 3, 4, 5, 6], 7, 9]
What I actually get back is 2 copies of the second list.