Search code examples
pythonloopspython-3.xn-queens

Producing a value based off a coordinate system


I'm stuck on a problem where we have to

build_board(coords,size):

Given a list of coordinates for the locations of 
int size, build a board (a list of lists of Booleans) of that size, and mark cells with a queen
True. 

Examples:

 build_board([(0,0)],1) → [[True]]

 build_board([(0,0)],2) → [[True,   False], [False, False]]

 build_board([(0,0),(1,1)],2) → [[True, False], [False, True]]

The context is that we made a function to make the board as such

def build_empty_board(size):
    size=int(size)
    ans = [ [False for x in range(size)] for x in range(size) ]
    return ans

However I don't know how to code a loop that checks each board made and produce values off a coordinate system. Could anyone guide me on how to code this?


Solution

  • What about this approach:

    def build_board(coords, size):
        # if any(i < 0 for coord in coords for i in coord):
        #     return
        board = [[False] * size for _ in range(size)]
        for (row, col) in coords:
            if row < 0 or col < 0:
                return
            board[row][col] = True
        return board
    
    print(build_board([(0,0)],1)) #[[True]]
    print(build_board([(0,0)],2)) #[[True,   False], [False, False]]
    print(build_board([(0,0),(1,1)],2)) #[[True, False], [False, True]]
    print(build_board([(0,0),(-1,3)],2)) #None