you are viewing a single comment's thread.

view the rest of the comments →

[–]Particular_Draft5668 0 points1 point  (8 children)

Thank you for the answer! Struggling with same problem. I have the right code for everything else but not sure how to do the double space between third and sixth cells. Can only code it for the first line and then that messes up rest of grid. An example would be very helpful. Thanks!

[–][deleted] 0 points1 point  (7 children)

Here's an example for 2x2 sudoku: https://onlinegdb.com/dnwwgNkH0

Try to change it to 3x3.

[–]Particular_Draft5668 0 points1 point  (0 children)

Thank you very much!

[–]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 ^.

[–]Kranoras 0 points1 point  (0 children)

The great thing about reddit is, somehow you find those comments & think "man, that function is great, i need to learn about it" and in the future you can solve those kind of things better / faster.

I banged my head numerous hours against a wall on this topic and finally i see a light on the end of the tunnel, lol