-8
我對他的數獨解算器使用的彼得·諾維格這個Python代碼。我不明白爲什麼assign應該爲'values'做任何事情,因爲在代碼中'values'沒有被更新,'values'只在if條件語句中被使用。你能解釋一下,先謝謝了!你能解釋Norvig的Sudoku代碼中的賦值功能嗎?
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,'')
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
for u in units[s]:
dplaces = [s for s in u if d in values[s]]
if len(dplaces) == 0:
return False ## Contradiction: no
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
正是你難道不明白是什麼? – DeepSpace
'消除'是做什麼的? 「替換」是做什麼的? –
調用函數後爲什麼值應該不同? – PythonRCpp