Python 即使使用复制方法也无故更改列表
Python list changing for no reason even with copy method
def return_solved_board(board):
solution = board.copy()
回溯递归循环开始
def solve(board):
for y in range(9):
for x in range(9):
if solution[y][x] == 0:
for number in range(1,10):
if check_rules_at_point(x, y, number, solution):
solution[y][x] = number
solve(solution)
#Where backtracking comes into play, if the solve method fails on the next cell than it resets current one.
solution[y][x] = 0
#Breaks out of recursion to try a differant number in cell prior
return
#Stores a solved copy of the solution into global variable
global returned_information
returned_information = solution.copy()
print(returned_information) #1st print statement
检查板子是否可以解决
if not check_for_valid_board(board):
return "This board is not possible to solve."
else:
solve(board)
global returned_information
print(returned_information) #2nd print statement
return returned_information
print(return_solved_board(valid_sudoku_board1))
我正在尝试编写一个解决数独谜题的程序。拼图存储在列表列表中。当我 运行 这个程序的第一个打印语句 returns 是正确解决的列表列表。但是,第二个 return 语句 return 是原始未解之谜。他们的两个 id 是相同的但是我不明白为什么 returned_information 在第二个打印语句中变回 returned_information 只被调用一次。
您可能遇到了字典/列表 copy()
是一个浅拷贝;使用 copy.deepcopy(...)
而不是进行深拷贝。
def return_solved_board(board):
solution = board.copy()
回溯递归循环开始
def solve(board):
for y in range(9):
for x in range(9):
if solution[y][x] == 0:
for number in range(1,10):
if check_rules_at_point(x, y, number, solution):
solution[y][x] = number
solve(solution)
#Where backtracking comes into play, if the solve method fails on the next cell than it resets current one.
solution[y][x] = 0
#Breaks out of recursion to try a differant number in cell prior
return
#Stores a solved copy of the solution into global variable
global returned_information
returned_information = solution.copy()
print(returned_information) #1st print statement
检查板子是否可以解决
if not check_for_valid_board(board):
return "This board is not possible to solve."
else:
solve(board)
global returned_information
print(returned_information) #2nd print statement
return returned_information
print(return_solved_board(valid_sudoku_board1))
我正在尝试编写一个解决数独谜题的程序。拼图存储在列表列表中。当我 运行 这个程序的第一个打印语句 returns 是正确解决的列表列表。但是,第二个 return 语句 return 是原始未解之谜。他们的两个 id 是相同的但是我不明白为什么 returned_information 在第二个打印语句中变回 returned_information 只被调用一次。
您可能遇到了字典/列表 copy()
是一个浅拷贝;使用 copy.deepcopy(...)
而不是进行深拷贝。