Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 递归帮助-Peter Norvig';s的数独练习_Python_Python 3.x_Recursion - Fatal编程技术网

Python 递归帮助-Peter Norvig';s的数独练习

Python 递归帮助-Peter Norvig';s的数独练习,python,python-3.x,recursion,Python,Python 3.x,Recursion,嗨,我现在正在学习Peter Norvig的数独解决方案() 但是,我对下面的块代码有点困惑: 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 = valu

嗨,我现在正在学习Peter Norvig的数独解决方案()

但是,我对下面的块代码有点困惑:

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
def分配(值、s、d):
“”“从值[s]中删除所有其他值(d除外)并传播。
返回值,如果检测到矛盾,则返回False
其他_值=值[s]。替换(d')
如果所有(消除其他_值中d2的(值s、d2)):
返回值
其他:
返回错误
def消除(值s、d):

“”“从值[s]中删除d;当值或位置Python
dict
s可变时传播,这意味着它们的值可以更改。”

此示例显示了一种反模式:您不应该同时对参数进行变异并返回它。例如,所有更改
列表的方法(
append
pop
等)都不返回原始列表

消除
函数与
分配
函数中的dict相同,分配函数中的任何更改都会反映在elimate函数中

以下是一个例子:

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

我明白了。所以即使dictionary不是一个全局对象,这也是一种行为?@AdrianPrayoga是的。Python参数是通过赋值传递的。也许可以更好地解释它。