这个生成器是如何工作的?它显然在外部 for 循环期间发生了变化。生成器是否在 for 循环期间进行评估?
代码改编自http://rosettacode.org/wiki/N-queens_problem#Python
如果我导入代码,它显示:
[[1, 3, 0, 2], [2, 0, 3, 1]]
在代码之前它说:
“对上述代码的一个令人惊讶的简单更改(将列表理解更改为生成器表达式)会产生回溯解决方案:”
class Solution:
# @return a list of lists of string
def under_attack(self, col, queens):
return col in queens or any(abs(col - x) == len(queens)-i for i,x in enumerate(queens))
def solve(self,n):
solutions = [[]]
for row in range(n):
solutions = (solution+[i] for solution in solutions
for i in range(n)
if not self.under_attack(i, solution))
print(list(solutions))
return solutions
A=Solution()
list(A.solve(4))