Application of iterative and recursive methods
ImportRandomdefPrettyprint (solution):#graphical processing of data defLine (Pos,length=len (solution)):#processing of single-row data return '.'* (POS) +'x'+'.'* (length-pos-1) forPosinchSolution:#draw a graph of every eight lines PrintLine (POS)defConflict (STATE,NEXTX):#detect if there is a conflictNexty =Len (state) forIinchRange (nexty):ifABS (STATE[I]-NEXTX)inch(0,nexty-i):#Compare by Distance returnTruereturnFalse#def Queens (Num,state):#If Len (state) = = Num-1:#For POS in range (num):#If not conflict (State,pos):#yield PosdefQueens (num=8,state=()): forPosinchrange (num):Print Stateif notconflict (state,pos):ifLen (state) ==num-1:#last one yield(POS,)#Iterative Methods Else: forResultinchQueens (Num,state+ (POS)):#recursive top seven data#Print Result yield(POS,) +resultPrint 'Bahuanghou'PrintList (Queens (4))#For I in List (Queens (8)):#Prettyprint (i)#print ' Next '#prettyprint (Random.choice (List (Queens (8) ))
Eight Queens--python code