How to solve the problem of python eight queens
This article mainly explains "how to solve the python eight queens problem". Friends who are interested might as well take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to solve the python eight queens problem.
Import random# conflict check, when defining state, state is used to mark the position of each queen, where the index is used to represent Abscissa, and the value corresponding to the base represents ordinate, for example: state [0] = 3, indicating that the queen is on the fourth column of row 1, def conflict (state, nextX): nextY = len (state) for i in range (nextY): # if the position of the next queen is adjacent to the current position of the queen (including upper and lower) (left and right) or on the same diagonal, it means that there is a conflict, and it is necessary to rearrange if abs (state [I]-nextX) in (0, nextY-i): return True return False# uses a generator to generate the position of each queen, and recursively realizes the position of the next queen. Def queens (num, state= ()): for pos in range (num): if not conflict (state, pos): # generate the position information of the current queen if len (state) = = num-1: yield (pos,) # otherwise, the position information of the current queen is added to the status list and passed to the next queen. Else: for result in queens (num, state+ (pos,)): yield (pos,) + result# in order to visually represent the chessboard, use X to represent the position of each queen def prettyprint (solution): def line (pos, length=len (solution)): return'. '* (pos) +' X'+'. '* (length-pos-1) for pos in solution: print line (pos) if _ _ name__ = = "_ _ main__": queens (8) prettyprint (random.choice (queens (8) so far, I believe you have a better understanding of "how to solve the Python eight queens problem". You might as well do it in practice! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!