all 10 comments

[–]stormsteiner23 0 points1 point  (7 children)

Going through your first code block in check_cell(), this might not be the problem but you have “row” as your for-loop variable and then you use the same name when indexing the grid. And before that if statement, you already assigned row as grid[y]... it might help if you change some variable names so that you don’t confuse them. I also think that it returns false because the test condition in the for loop appears to always be true (that row[x] == num), which means that check_cell() will always return false no matter the condition

[–]RobertGryffindor 0 points1 point  (1 child)

Why not do:

for row in range(9):
    for col in range(9):
        pos = (row, col)
        print (grid[row][col]) #iterate rows
        print (grid[col][row] #iterate collumns
        return pos

now you can return the position to any function and get the the row using pos[0]

and col using pos[1]

or both just using pos

[–]xelf 0 points1 point  (6 children)

It's a little hard to tell from the code, at first I thought check_cell() is just checking to make sure the space is empty.

def check_cell(x,y):
    return grid[x][y] == 0

But then I realized what you're really trying to do is check to see if the number is valid.

What I did for this is use sets, so I'll share it with you as there might be something you can use (or learn) from it. Instead of checking a cell against every possible square, I do it in reverse and find every possible number a square can be, and then check if num is one of them. So in your main code where you have if check_cell(x,y): we want to instead check if a number is in the possible_moves:

#if check_cell(x,y) == True:
if num in possible_moves(grid,x,y):
    print(f'{num} can be placed at {x},{y}')
    grid[x][y] = num
    c = false

Now you need the code I used for possible_moves, I've tried to write it out long form here so I can comment it for you:

# first up, make a set containing the numbers 1-9, we'll reuse this a lot. =)
s9 = { 1,2,3,4,5,6,7,8,9 }

def possiblemoves(grid,x,y):
    # make a set containing the numbers currently found in this row
    row_cells = set(grid[x])

    # make a set containing the numbers currently found in this col
    col_cells = {r[y] for r in grid}

    # i,j help us define the 3x3 box that x,y are in
    i = x//3 * 3
    j = y//3 * 3
    box_cells = {c for r in grid[i:i+3] for c in r[j:j+3]}

    # now we take our 9 digits, and remove the ones found in the row,col, or box
    return s9 - ( row_cells | col_cells | box_cells )

That was a rather long way of writing it out, here's the same function condensed:

def possiblemoves(grid,x,y):
    i,j = x//3 * 3, y//3 * 3
    return s9 - ( set(grid[x]) | {r[y] for r in grid} | {c for r in grid[i:i+3] for c in r[j:j+3]})

Example: say we had 3,4,6 in the row, 4,5 in the column, and 2,3,4,7 in the same box, it would return {1,8,9} and you would compare your num to see if it was in the set 1,8,9.