Check if number already contains in row and column

Asked

Viewed 36 times

-1

Good evening, I need to do a sudoku, and the first part is to print an array with random number from 1 to 9 and check if that number already has in the row and column. I did it:

import random
matriz = []
for i in range(9):
    linha = []
    for j in range(9):
        aleatorio = random.randint(1, 9)
        if aleatorio != i and aleatorio != j:
            linha.append(aleatorio)
        matriz.append(linha)

for i in range(9):
    print(matriz[i])

But it doesn’t work, when I print the matrix sometimes gets a line and column less or more, and the numbers repeat. Someone can help me?

  • Are you trying to generate a complete table with random numbers? Are you sure this will work? I am not saying, but I believe that in Sudoku, just because a number can be inserted into a given cell, does not mean that it should be inserted. Often you may end up locking the table with these actions.

1 answer

1


Check if the number already exists in the list before adding, so you avoid it repeating itself. And using the while causes it to repeat until it fills the list.

Source of the code: Link

result = []
while len(result) != 4:
    r = randint(0, 100)
    if r not in result:
        result.append(r)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.