[英]Recursion help - Peter Norvig's Sudoku exercise
嗨,我目前正在使用Peter Norvig的數獨解決方案( http://norvig.com/sudoku.html )。
但是,我對下面的代碼有些困惑:
def assign(values, s, d):
"""Eliminate all the other values (except d) from values[s] and propagate.
Return values, except return False if a contradiction is detected."""
other_values = values[s].replace(d, '')
if all(eliminate(values, s, d2) for d2 in other_values):
return values
else:
return False
def eliminate(values, s, d):
"""Eliminate d from values[s]; propagate when values or places <= 2.
Return values, except return False if a contradiction is detected."""
if d not in values[s]:
return values ## Already eliminated
values[s] = values[s].replace(d,'')
## (1) If a square s is reduced to one value d2, then eliminate d2 from the peers.
if len(values[s]) == 0:
return False ## Contradiction: removed last value
elif len(values[s]) == 1:
d2 = values[s]
if not all(eliminate(values, s2, d2) for s2 in peers[s]):
return False
## (2) If a unit u is reduced to only one place for a value d, then put it there.
for u in units[s]:
dplaces = [s for s in u if d in values[s]]
if len(dplaces) == 0:
return False ## Contradiction: no place for this value
elif len(dplaces) == 1:
# d can only be in one place in unit; assign it there
if not assign(values, dplaces[0], d):
return False
return values
函數assign
接收字典values
的輸入,如果沒有矛盾,則也將返回values
。 但是,在assign
函數中,我沒有看到字典values
任何更新。 我的理解是,dict values
是使用eliminate
功能更新的(在運行代碼后,我相信是這種情況)。 但是,這是在assign
函數之外完成的,並且不應影響assign函數中的values
,因為它不會直接在函數中更新。
也許你們可以給我帶來一點曙光?
Python dict
是可變的,這意味着它們的值可以更改。
這個例子顯示了一個反模式:您不應該同時變異一個參數並返回它。 一個示例是所有更改list
的方法( append
, pop
等) 均不返回原始列表。
eliminate
函數與assign
函數具有相同的 dict,並且assign
函數中的任何更改都反映在消除函數中。
這是一個例子:
def update(dict_, key, value):
dict_[key] = value
d = {
1: 2,
3: 4
}
update(d, 1, 100)
update(d, 3, 100)
print(d[1] + d[3]) # 200
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.