eight queens problem in Python

后端 未结 4 1393
自闭症患者
自闭症患者 2021-02-03 16:34

8-queens problem in Python.

Hi! I only start teaching Python, so could someone explain the code written below (found in the Internet)? Some pieces of the code are compli

4条回答
  •  心在旅途
    2021-02-03 16:57

    This is the source program where the output of this code will be generated in the separate file name as "queen.txt"

    import json
    import sys
    
    BOARD_SIZE = 8
    
    def under_attack(col, queens):
        x = y = col
    
        for r, c in reversed(queens):
            x , y = x - 1, y + 1 #check for the prev queen location 
    
            if c in (x , col, y):
                return True
        return False
    
    def solve(n): # n is the number of queens to be placed
        if n == 0:
            return [[]]
    
        smaller_solutions = solve(n - 1)
    
        return [solution+[(n,i+1)]
            for i in xrange(BOARD_SIZE)
                for solution in smaller_solutions
                    if not under_attack(i+1, solution)] #call the function 
    
    former, sys.stdout = sys.stdout, open('queen.txt','w')
    
    for answer in solve(BOARD_SIZE):
        print answer
    
    results, sys.stdout = sys.stdout, former #former is used for ip & op
    print json.dumps(answer) #dumps is used to write in json file
    

    output file will like this [(1, 4), (2, 2), (3, 7), (4, 3), (5, 6), (6, 8), (7, 5), (8, 1)] [(1, 5), (2, 2), (3, 4), (4, 7), (5, 3), (6, 8), (7, 6), (8, 1)] [(1, 3), (2, 5), (3, 2), (4, 8), (5, 6), (6, 4), (7, 7), (8, 1)] . . . . [(1, 4), (2, 7), (3, 5), (4, 2), (5, 6), (6, 1), (7, 3), (8, 8)] [(1, 5), (2, 7), (3, 2), (4, 6), (5, 3), (6, 1), (7, 4), (8, 8)]

提交回复
热议问题