我的函数在调用时返回错误的值。首先,迭代返回正确的值,但是如果我调用一个新函数,则返回正确的值。为什么返回非空列表?
我在shell中运行了以下代码。最后一个调用应返回一个空列表,但它会返回之前调用中的返回值。
>>> from solvers.algorithms.dancing_links import solve
>>> solve({}, {})
[]
>>> solve(ctor, rtoc)
['B', 'D', 'F']
>>> solve(ctor, rtoc)
['B', 'D', 'F']
>>> solve({}, {})
['B', 'D', 'F']
这是我的python代码。
# Solves the Sudoku using dancing links algorithm using implementation from:
# https://www.cs.mcgill.ca/~aassaf9/python/algorithm_x.html
def solve(columns_to_rows, rows_to_columns, solution=[]):
"""
This function solves the exact cover problem, i.e., given a matrix A in which each element is 0 or 1.
Is there a subset of rows which have exactly one 1 in each column?
The exact cover problem can also be stated as following,
"Given a set X and a set of subsets of X called Y, is there a subset of Y such that all of its elements
are disjoint and union of its elements is X."
:param columns_to_rows: It is a dictionary where value of key `i` is the set of columns in which ith row is 1.
:param rows_to_columns: It is a dictionary where value of key `i` is the set of rows in which ith column is 1.
:param solution: Currently selected rows
:return:
"""
if not columns_to_rows:
return list(solution)
else:
# Column with minimum 1's in it.
selected_column = min(columns_to_rows, key=lambda col: columns_to_rows[col])
# For each row which has a 1 in the `selected_column`.
for selected_row in columns_to_rows[selected_column]:
solution.append(selected_row)
# Select and remove all columns which have 1's in the `selected_row`
# Also remove all the rows which have 1's in the same column as the `selected_row`
removed_columns = select_and_remove(columns_to_rows, rows_to_columns, selected_row)
tmp = solve(columns_to_rows, rows_to_columns, solution)
if tmp is not None:
return tmp
deselect_and_insert(columns_to_rows, rows_to_columns, selected_row, removed_columns)
solution.pop()
编辑1:我添加了一条打印语句以打印“ solution”变量,然后发现了这一点。
>>> from solvers.algorithms.dancing_links import solve>>> solve({}, {})
[]
[]
>>> solve({}, {})
[]
[]
>>> solve(ctor, rtoc)
[]
['A']
['B']
['B', 'D']
['B', 'D', 'F']
['B', 'D', 'F']
>>> solve({}, {})
['B', 'D', 'F']
['B', 'D', 'F']
>>>
因此,当我第一次调用该函数时,它返回空列表,解决方案也为空。然后,当我第二次使用实际参数调用该函数时,该函数将按预期工作并进入递归调用。但是第三次将解决方案变量设置为先前的值,但应为空。为什么会这样呢?以及如何解决?
不要将solution=[]
传递给函数,它会将其保存为引用并可能影响您的结果,每次函数运行时都传递一个新列表
更多信息:here