迭代和递归方法的运用
import random def prettyprint(solution): #图形化处理数据 def line(pos,length=len(solution)): #单行数据的处理 return '.'*(pos) + 'x'+'.'*(length-pos-1) for pos in solution: #画出每八行的图 print line(pos) 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,state): # if len(state) == num-1: # for pos in range(num): # if not conflict(state,pos): # yield pos def queens(num=8,state=()): for pos in range(num): print state if not conflict(state,pos): if len(state)==num-1: #最后一个 yield (pos,) #迭代方法 else: for result in queens(num,state+(pos,)): #递归前七个数据 # print result yield(pos,)+result print 'bahuanghou' print list(queens(4)) #for i in list(queens(8)): # prettyprint(i) # print 'next' #prettyprint(random.choice(list(queens(8))))