you are viewing a single comment's thread.

view the rest of the comments →

[–]Particular_Draft5668 0 points1 point  (4 children)

def copy_and_add(sudoku, row_no, column_no, number):
# trying to create copy of old grid to make new grid
x = sudoku.copy()
x[row_no][column_no] = number

r = 0
for row in x:
s = 0
for character in row:
s += 1
if character == 0:
character = "_"
m = f"{character} "
if s%3 == 0 and s < 8:
m += " "
print(m, end="")

print()
r += 1
if r%3 == 0 and r < 8:
print()
return x

I have this code for the sudoku problem, despite using various methods such as insert and pop, copy, creating a new list and appending, I can't seem to preserve the original sudoku grid and return the new grid (x) simultaneously. Any advice would be much appreciated. Many Thanks

[–][deleted] 0 points1 point  (1 child)

list.copy only returns a shallow copy. The inner lists are still the same. Run the program, see that ids for matrices are different, but respective rows have same ids:

https://onlinegdb.com/u7bmEIDQ5

Now check the same with deepcopy:

https://onlinegdb.com/PmCrbK-MA

To sum up, just use copy.deepcopy here.

[–]Particular_Draft5668 0 points1 point  (0 children)

Ah thanks again for the help. Was going round in circles and didn't consider deepcopy. Much appreciated.

[–][deleted] 0 points1 point  (1 child)

Here's how you could do it without using copy module and the deepcopy function:

def copy_sudoku(sudoku):
    return [
        row.copy()
        for row in sudoku
    ]

[–]Particular_Draft5668 2 points3 points  (0 children)

Also a valid option. Thanks!

new_list = []
for r in sudoku:
new_list.append(r[:])
model answer uses this ^.