def conflict(state, nextX):
nextY = len(state)
for i in range(nextY):
if abs(state[i]-nextX) in (0, nextY-i):
return True
return False
def queens(num=8, state=()):
for pos in range(num):
if not conflict(state, pos):
if len(state) == num-1:
yield (pos,)
else:
results=queens(num, state + (pos,))
for res in results:
yield (pos,) + res
print list(queens(8))
这是八个皇后的解决方案,效果很好。但是当我做了一点改变时。python 生成器中的 next() 方法变得很奇怪。
def conflict(state, nextX):
nextY = len(state)
for i in range(nextY):
if abs(state[i]-nextX) in (0, nextY-i):
return True
return False
def queens(num=8, state=()):
for pos in range(num):
if not conflict(state, pos):
if len(state) == num-1:
yield (pos,)
else:
results=queens(num, state + (pos,))
for res in results:
yield (pos,) +results.next() //here is the change. res -->results.next()
print list(queens(8))
它只是打印一个[]。我多么尴尬!我不明白为什么 next() 方法在任何其他情况下都有效,但在这里却不行。