1 def conflict(state,nextX):
2 nextY=len(state)
3 for i in range(nextY): #注意range是一个半开半闭区间,左闭右开
4 if abs(state-nextX) in (0,nextY-i): #这里是python中我很喜欢的一个特性,比同样的C语言代码简单很多。
5 return True
6 return False
7
8 def queens(num=8,state=()): #默认参数,与C++的规则一样,从右到左必须都存在默认参数,即如果一个默认参数的右方还存在没有默认值的参数,会出错。
9 for pos in range(num):
10 if not conflict(state,pos):# if not语句
11 if len(state)==num-1:
12 yield (pos,) #yield生成器,生成tuple,注意(pos,)这样的格式
13 else:
14 for result in queens(num,state+(pos,)): #tuple等数据结构的连接也是我很喜欢python的一个原因。
15 yield (pos,)+result
16 def pretty_print(solution):
17 def line(pos,length=len(solution)):#函数定义中定义函数,这一点与C/C++都不同,需要额外注意。
18 return '.'*pos+'X'+'.'*(length-pos-1)
19 for pos in solution:
20 print line(pos)
21 #print list(queens(4))
22 #print len(list(queens(8)))
23 import random
24 pretty_print(random.choice(list(queens(8))))
"学而不思则惘"。总结十分重要!
参考资料:《Beginning Python From Novice to Professional 2nd Edition》