'uneven grid in Sudoku after adding number

I am trying to write a code to print out sudoku grid and then add the value to the grid by calling another function.

After adding the value, the grid layout seems to getting messed up. Any help would be appreciated.

def print_sudoku(sudoku: list):
    counter = 0
    for row in sudoku:
        for cell in row:
            counter += 1
            if cell == 0:
                print("_ ", end="")
                if counter % 3 == 0:
                    print(" ", end="")
                if counter % 9 == 0:
                    print()
                if counter % 27 == 0:
                    print()
            else:
                print(cell, end=" ")


def add_number(sudoku: list, row_no: int, column_no: int, number:int):
    sudoku[row_no][column_no]=number

sudoku  = [
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0]
]

print_sudoku(sudoku)
add_number(sudoku, 0, 0, 2)
add_number(sudoku, 1, 2, 7)
add_number(sudoku, 5, 7, 3)
print()
print("Three numbers added:")
print()
print_sudoku(sudoku)

output: enter image description here



Solution 1:[1]

The issue is that that only when you put a number in a column number that is divisible by 3, 9, 27 are you getting messed up whitespace.

Well why is this happening? Because the way you decide to print whitespace based on the value of counter is only ran in this section of your code:

if cell == 0:
    if counter % 3 == 0:
        print(" ", end="")
    if counter % 9 == 0:
        print()
    if counter % 27 == 0:
        print()

However, if the cell is not empty: if cell == 0 your program will never to get to those nested if statements.

The solution is to put those if statements checking at the end of the loop outside any if statements so that they will be checked every loop regardless of the value of cell.

if cell == 0:
    ....
else:
    ....
if counter % 3 == 0:
    print(" ", end="")
if counter % 9 == 0:
    print()
if counter % 27 == 0:
    print()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1