1 ImportRandom2 #The conflict check, when defining state, uses state to flag each queen's position, where the index is used to denote the horizontal axis, and the base corresponding value represents the ordinate, for example: State[0]=3, which indicates that the Queen is on the 4th column of row 1th3 defconflict (state, NEXTX):4Nexty =Len (state)5 forIinchRange (nexty):6 #if the next queen's position is adjacent to the current Queen's position (both up and down, left and right) or on the same diagonal, then there is a conflict and needs to be rearranged7 ifABS (STATE[I]-NEXTX)inch(0, nexty-i):8 returnTrue9 returnFalseTen One #The generator is used to generate the position of each queen, and the next Queen's position is realized by recursion. A defQueens (num, state=()): - forPosinchrange (num): - if notConflict (State, POS): the #generate location information for the current queen - ifLen (state) = = Num-1: - yield(POS,) - #Otherwise, add the location information of the current queen to the status list and pass it on to the next queen. + Else: - forResultinchQueens (num, state+(POS,)): + yield(POS,) +result A at - #to visualize the chessboard, use X to indicate the position of each queen. - defPrettyprint (solution): - defLine (POS, length=len (solution)): - return '. '* (POS) +'X'+'. '* (length-pos-1) - forPosinchSolution: in PrintLine (POS) - to if __name__=="__main__": +Prettyprint (Random.choice (List (Queens (8)))
Python learns the eight Queens question