此 return 语句究竟指示程序执行什么操作



这是一个递归解决方案,来自 https://wiki.python.org/moin/SimplePrograms 的8皇后问题。我很难理解解决函数中的返回语句如何/为什么工作。乍一看,它似乎违反了规则(例如,解决方案尚未在 return 语句的循环之前声明或同化值,但它出现在 return 语句的循环之前(,但我可以成功运行它,所以我很好奇它是如何工作的以及为什么有人可能选择这样写(令人困惑? 短? 因为其他限制我还不明白?(

BOARD_SIZE = 8
def under_attack(col, queens):
    left = right = col
    for r, c in reversed(queens):
        left, right = left - 1, right + 1
        if c in (left, col, right):
            return True
    return False
def solve(n):
    if n == 0:
        return [[]]
    smaller_solutions = solve(n - 1)
    return [solution+[(n,i+1)]
        for i in xrange(BOARD_SIZE)
            for solution in smaller_solutions
                if not under_attack(i+1, solution)]
for answer in solve(BOARD_SIZE):
    print answer

熟悉一些实验和我参加的课程中问题的递归解决方案,但我对整个 python 很陌生(我主要在课堂上使用 java 和 C(。

有没有人有很好的方法来解释这种语法是如何工作的,或者我可以研究的其他例子来帮助我理解它?这真的让我的好奇心痒痒的...

我想你的困惑是这行代码:

       v---- this starts the list
return [solution+[(n,i+1)]
        for i in xrange(BOARD_SIZE)
            for solution in smaller_solutions
                if not under_attack(i+1, solution)]
                                                  ^-- this ends the list

这实际上是一种列表理解,一种创建列表的简略方法。

这是该循环的手写版本。

x = []
for i in xrange(BOARD_SIZE):
    for solution in smaller_solutions:
        if not under_attack(i+1, solution):
            x.append(solution+[(n, i+1)])
return x

您正在询问列表推导。这是Python进行功能映射(将函数应用于列表的每个元素(和过滤器(在某些条件下过滤列表(的方式。

解释这一点的最简单方法是使用一些示例。

说:

>>> l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> [2 * i for i in l]
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
>>> [i for i in l if i > 5]
[6, 7, 8, 9, 10]

现在这些可以组合在一起,您可以使用任意数量的 for:

>>> # squares of even numbers below 10
>>> [i * i for i in range(10) if i%2 == 0]
[0, 4, 16, 36, 64]
>>> # concatenating all lists
>>> ll = [[1, 2], [3, 4], [5, 6], [7, 8], [8, 10]]
>>> [i for l in ll for i in l]
[1, 2, 3, 4, 5, 6, 7, 8, 8, 10]

最新更新