你能解释Norvig的Sudoku代码中的赋值函数吗?

时间:2017-07-19 13:29:06

标签: python algorithm constraints sudoku

Peter Norvig在他的数独求解器中使用了这个Python代码。我不明白为什么assign应该对'values'做任何事情,因为因为没有代码中的哪个地方'values'得到更新而'values'只用在if条件语句中。请你解释一下,提前谢谢!

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

1 个答案:

答案 0 :(得分:0)

values已更新为eliminate的副作用:

values[s] = values[s].replace(d,'')

这会从d的{​​{1}}条目中删除所有值s。请参阅replace