八皇后问题的进化(4)-python写的八皇后

这是“Beginning Python From Novice to Professional”里用python写的八皇后,代码量很少,用到了生成器。

python一直给我的感觉是:你可以全心全意用简洁的语言编程,而不用太关心语法问题,用C像是写报告,而用python更像是写诗。


# 8 queens

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:
				for result in queens(num,state + (pos,)):
					yield (pos,) + result				
	
#show all solution
for solution in queens(8):
	print solution	

#count solution 
print "The number of solutions is :"
print len(list(queens(8)))		

转载本文请注明作者和出处[Gary的影响力]http://garyelephant.me,请勿用于任何商业用途!

Author: Gary Gao 关注互联网、分布式、高并发、自动化、软件团队
支持我的工作:  https://me.alipay.com/garygao

你可能感兴趣的:(编程,python,list,语言,conflict)