美文网首页
8 Queens' Problem (Solved by Pyt

8 Queens' Problem (Solved by Pyt

作者: 马芬奇 | 来源:发表于2017-07-12 18:46 被阅读0次
    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)

    相关文章

      网友评论

          本文标题:8 Queens' Problem (Solved by Pyt

          本文链接:https://www.haomeiwen.com/subject/pxtihxtx.html