八皇后问题的进化(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)))		


你可能感兴趣的:(python)