1

For some reason, the list solutions keeps getting cleared and filled with empty lists instead of lists of lengths of 9. Not sure why, the variable isn't used anywhere else

def check_valid(board, n):
    for i in range(len(board)):
        if i >= n*(n-1):
            return True
        try:
            #If not Right End
            if (i+1)%n != 0:
                if board[i] == board[i+n+1] == 1: #If same as bottom right 1
                    return False
                if -1*board[i] == board[i+1]: #If opposite of adjacent right
                    return False
            #If not Left End
            if i%n != 0:
                if board[i] == board[i+n-1] == -1: #If same as bottom left -1
                    return False
        except IndexError:
            continue
    return True

solutions = []

def run_board(board, n):
    if len(board) == n**2:
        print(board)
        solutions.append(board)
        if solutions[-1] == [1, 1, 1, 1, 0, -1, 1, 0, 1]:
            print('lol')
        return
    for k in [-1, 0, 1]:
        board.append(k)
        if check_valid(board, n):
            run_board(board, n)
        board.pop()
        

run_board(board = [], n = 3)


print(solutions)

I don't know if this has something to do with the function running recursively and weird scoping

Kinshu
  • 54
  • 5
  • `solutions.append(board)` doesn't make a copy of `board`; all subsequent changes to `board` will be visible in the final value of `solutions`. You want something like `solutions.append(board.copy())` to take a snapshot of the solutions that are found. – jasonharper May 25 '21 at 23:54

1 Answers1

1

Instead of plain append(board) you can use

solutions.append(board.copy())

This seems to not output empty lists.

Buddy Bob
  • 5,829
  • 1
  • 13
  • 44
  • It does work now, thanks. But I don't understand why. I know that reassigning a list to another list simply points to the same list, but why does this happen with appending? Furthermore, while debugging the code, the `solutions` variable did get appended to while running. – Kinshu May 26 '21 at 01:31