Mal*_*fat 2 python recursion return
这是来自https://wiki.python.org/moin/SimplePrograms的8皇后问题的递归解决方案.我很难理解solve函数中return语句的工作方式/原因.乍一看,它看起来像是破坏了规则(比如,在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
Run Code Online (Sandbox Code Playgroud)
我熟悉从一些实验和我所采取的课程中解决问题的递归解决方案,但我对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
Run Code Online (Sandbox Code Playgroud)
这实际上是一个列表理解,一种创建列表的简便方法.
这是该循环的简写版本.
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
Run Code Online (Sandbox Code Playgroud)