python的yield用法,
若一个函数中有yield,就不能有return,有了yield,此函数就变成了一个生成器。更直观一点说,他的结果是一个list列表。
View Code
1 # -*- coding: utf-8 -*- 2 def conflict(state, nextX): 3 length = len(state) 4 for i in range(length): 5 if abs(state[i] - nextX) in (0, length - i): 6 return True 7 return False 8 9 def queens(num = 8, state = ()): 10 for i in range(num): 11 if not conflict(state, i): 12 if num - 1 == len(state): 13 yield (i,) 14 else: 15 for j in queens(num, state + (i, )): 16 yield j + (i, ) 17 18 print len(list(queens()))
得好好理解一下yield用法! 具体算法的注释请自己看《python基础教程》