def conflict(state,nextX):
nextY=len(state) #next row
for i in range(nextY): #go through 0 to nextY-1 rows
if abs(state[i]-nextX) in (0,nextY-i):
return True
return False
def queens(num,state): #output a sequence
if len(state)==num-1: #last row
for pos in range(num): #go throuth 0 to num-1 columns
if not conflict(state,pos): #if not conflict
yield (pos,) #generate a tuple(pos,)
else:
for pos in range(num): #go throuth 0 to num-1 columns
if not conflict(state,pos): #if not conflict
for result in queens(num,state+(pos,)): #go through next queens()'results
yield (pos,)+result #generate a (pos,)+a next queens()'result
def prettyprint(solution):
def line(pos,length=len(solution)):
return '. '*(pos)+'X '+'. '*(length-pos-1)
for pos in solution:
print(line(pos))
import random
prettyprint(random.choice(list(queens(8,()))))
Results ( A Example ):
Functions and Statements:
(1) def [function name] ( [parameters] ):
[return or no return]
[yield]
(2) len( [object] )
(3) print( [strings] )
(4) range( [num] )=[0,1,2,...,num-1]
(5) list( [sequence] )=[sequence]
Methods:
(1)Recursion
A Example:
def factorial(n):
if n==1:
return 1 # ending condition
else:
return n*factorial(n-1) # recursive formula
Reference:
Beginning Python From Novice to Professional (2nd Edition)