Python |返回变量

2024-06-02 09:21:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我阅读并理解了other question中描述的整篇文章。

我的问题是关于这个source code

作者在函数assign中返回值:

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

但是assign从未用于在调用函数parse_grid(grid)时设置现有的变量值:

def parse_grid(grid):
    values = dict((s, digits) for s in squares)
    for s,d in grid_values(grid).items():
        if d in digits and not assign(values, s, d):
            return False ## (Fail if we can't assign d to square s.)
    return values

所以对我来说,回归价值观似乎是不必要的。因为他只使用assign()作为布尔值,所以不能直接返回true吗?

我知道返回值不会改变原始变量的任何内容。只有当变量作为参数传递并在那里更改而没有返回到另一个变量时,“original”变量才会更改,因为它持有相同的引用。

但是def parse_grid(grid中的return values)应该是一个完全改变的值,然后是函数开头的值。什么时候分配?

问题:

def parse_grid(grid中的values在哪里更改?因为此函数返回值,并且此返回值不应与此函数开始时设置的值相同。那么它是在哪里被改变的,又是如何改变的呢?

它的调用方式如下:display(parse_grid(grid2))


Tags: 函数infalseforreturnifparsedef
3条回答

assign函数被多次调用。例如,在搜索功能中:

def search(values):
    "Using depth-first search and propagation, try all possible values."
    if values is False:
        return False ## Failed earlier
    if all(len(values[s]) == 1 for s in squares): 
        return values ## Solved!
    ## Chose the unfilled square s with the fewest possibilities
    n,s = min((len(values[s]), s) for s in squares if len(values[s]) > 1)
    return some(search(assign(values.copy(), s, d)) 
        for d in values[s])

assign的返回值传递到search以继续深度优先搜索。

让我们来看看这个函数:

def parse_grid(grid):
    values = dict((s, digits) for s in squares)
    for s,d in grid_values(grid).items():
        if d in digits and not assign(values, s, d):
            return False ## (Fail if we can't assign d to square s.)
    return values

在这里,函数返回一个新的dict。它返回它,以便调用者可以处理它。函数不返回True,因为调用方希望获取并使用新的dict

在您显示的代码中,assign似乎未被充分使用。你说得对:它只用于检查值的有效性(一个没有矛盾的测试)。 所以,正如你所说,回归真实就可以了。

但是既然assign可以做更多的事情,为什么要破坏它呢?它可能在代码的其他地方有用。


编辑:事实上是这样。查看链接的代码,函数search调用它并使用返回值。

相关问题 更多 >