根据坐标系生成值

时间:2016-03-28 02:25:55

标签: python loops python-3.x n-queens

我遇到了一个问题,我们必须

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. 

示例:

 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]]

上下文是我们制定了一个功能,使董事会成为这样的

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

但是我不知道如何编写一个循环来检查每个电路板,并从坐标系中产生值。任何人都可以指导我如何编码吗?

1 个答案:

答案 0 :(得分:1)

这种方法怎么样:

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