发布时间:2019-09-15 09:59:30编辑:auto阅读(1897)
- def conflict(state,nextX):
- nextY=len(state)
- for i in range(nextY): #注意range是一个半开半闭区间,左闭右开
- if abs(state[i]-nextX) in (0,nextY-i): #这里是python中我很喜欢的一个特性,比同样的C语言代码简单很多。
- return True
- return False
- def queens(num=8,state=()): #默认参数,与C++的规则一样,从右到左必须都存在默认参数,即如果一个默认参数的右方还存在没有默认值的参数,会出错。
- for pos in range(num):
- if not conflict(state,pos):# if not语句
- if len(state)==num-1:
- yield (pos,) #yield生成器,生成tuple,注意(pos,)这样的格式
- else:
- for result in queens(num,state+(pos,)): #tuple等数据结构的连接也是我很喜欢python的一个原因。
- yield (pos,)+result
- def pretty_print(solution):
- def line(pos,length=len(solution)):#函数定义中定义函数,这一点与C/C++都不同,需要额外注意。
- return '.'*pos+'X'+'.'*(length-pos-1)
- for pos in solution:
- print line(pos)
- #print list(queens(4))
- #print len(list(queens(8)))
- import random
- pretty_print(random.choice(list(queens(8))))
"学而不思则惘"。总结十分重要!参考资料:《Beginning Python From Novice to Professional 2nd Edition》
如果我的文章对您有用,请"赞"一下,非常感谢!
上一篇: wing 切换python版本
下一篇: 3G上网卡连接报错信息大全
48726
47765
38536
35732
30170
26909
25937
20782
20549
18938
325°
402°
437°
455°
445°
434°
486°
556°
667°
685°