Python全局列表在递归函数中追加后不断被清除



由于某些原因,列表solutions不断被清除,并用空列表填充,而不是长度为9的列表。不知道为什么,该变量没有在其他任何地方使用

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)

我不知道这是否与递归运行的函数和奇怪的范围有关

您可以使用而不是普通的append(board)

solutions.append(board.copy())

这似乎不会输出空列表。

最新更新