Python example sharing --- logic reasoning programming solves eight queens, python logic reasoning
It can match the pattern like Haskell and Prolog,
Create logic to push to rules, describe the question, and get the answer.
from pyDatalog import pyDatalogpyDatalog.create_atoms( 'N, N1, X, Y, X0, X1, X2, X3, X4, X5, X6, X7' )pyDatalog.create_atoms( 'ok, queens, next_queen, pred, pred2' )size = 8ok( X1, N, X2 ) <= ( X1 != X2 ) & ( X1 != X2 + N ) & ( X1 != X2 - N )pred( N, N1 ) <= ( N > 1 ) & ( N1 == N - 1 )queens( 1, X ) <= ( X1._in( range( size ) ) ) & ( X1 == X[0] )queens( N, X ) <= pred( N, N1 ) & queens( N1, X[:-1] ) & next_queen( N, X )pred2( N, N1 ) <= ( N > 2 ) & ( N1 == N - 1 )next_queen( 2, X ) <= ( X1._in( range( 8 ) ) ) & ok( X[0], 1, X1 ) & ( X1 == X[1] )next_queen( N, X ) <= pred2( N, N1 ) & next_queen( N1, X[1:] ) & ok( X[0], N1, X[-1] ) print( queens( size, ( X0, X1, X2, X3, X4, X5, X6, X7 ) ) )
Python solves the eight Queens algorithm
Global col # define some global variables
Global row
Global pos_diag
Global nag_diag
Global count
Def output ():
''' Outputs a valid result.
'''
Global count
Print row
Count + = 1
Def do_queen (I ):
''' Generates all correct solutions
@ Param I: Number of queens
'''
For j in range (0, 8): # Try 0 ~ 7 Location
If col [j] = 1 and pos_diag [I-j + 7] = 1 and nag_diag [I + j] = 1: # if this row has a diagonal line, if there is no queen on the negative diagonal, add it to queen I.
Row [I] = j
Col [j] = 0 # adjust the status of each list
Pos_diag [I-j + 7] = 0
Nag_diag [I + j] = 0
If I <7:
Do_queen (I + 1) # Can be incremented or decreased
Else:
Output () # generate a result and output
Col [j] = 1 # restore the previous status of each list
Pos_diag [I-j + 7] = 1
Nag_diag [I + j] = 1
If _ name _ = '_ main __':
Col = [] # list of matrix columns, storing the Queen's column. If this column does not have a queen, set it to 1. Otherwise, set it to 0.
Row = [] # A List Of Matrix rows that store the positions of the columns where the queen of each row is located. With the execution of the program, the results are output in constant changes.
Pos_diag = [] # diagonal line, I-j constant,-7 ~ 0 ~ 7, and B (I) + 7 are unified to 0 ~ 14
Nag_diag = [] # negative diagonal, I + j constant, 0 ~ 14
Count = 0
For index in range (0, 8): # Some initialization work
Col. append (1)
Row. append (0)
For index in range (0, 15 ):
Pos_diag.append (1)
Nag_diag.append (1)
Do_queen (0) ...... remaining full text>
Python has minor logic problems in determining conflicting functions
If the code is indeed incorrect, the return position is incorrect. In addition, the answer to your question is that the slope of the Two-point connection is 1 or 1, that is, the absolute value of the x-axis offset is equal to the vertical offset.