如何找到 "pos" 的行、列?

How find row, col with "pos"?

我必须完成解决数独的代码。 问题如下,需要编写输出行/列/方块坐标的代码。 根据条件,指定“pos”,借助于它传输坐标。 我尝试以不同的方式写作,但没有放弃。 我寻求帮助! 下面是带注释的代码。

位置 = (0, 0)

行,col = pos

row = grid[pos[0]]

的正确代码
def get_row(grid: tp.List[tp.List[str]], pos: tp.Tuple[int, int]) -> list[str]:

"""**Returns all values ​​for the line number given by pos**
>>> get_row([['1', '2', '.'], ['4', '5', '6'], ['7', '8', '9']], (**0**, 0))
**['1', '2', '.']**
>>> get_row([['1', '2', '3'], ['4', '.', '6'], ['7', '8', '9']], (**1**, 0))
**['4', '.', '6']**
>>> get_row([['1', '2', '3'], ['4', '5', '6'], ['.', '8', '9']], (**2**, 0))
**['.', '8', '9']**
"""

    return grid[pos[0]]  **# this is the correct code**

def get_col(grid: tp.List[tp.List[str]], pos: tp.Tuple[int, int]) -> tp.List [str]:

"""Returns all values ​​for the column number given by pos
>>> get_col([['1', '2', '.'], ['4', '5', '6'], ['7', '8', '9']], (0, 0))
**['1', '4', '7']**
>>> get_col([['1', '2', '3'], ['4', '.', '6'], ['7', '8', '9']], (0, 1))
**['2', '.', '8']**
>>> get_col([['1', '2', '3'], ['4', '5', '6'], ['.', '8', '9']], (0, 2))
**['3', '6', '9']**
"""
pass  #  **???**

def get_block(grid: tp.List[tp.List[str]], pos: tp.Tuple[int, int]) -> tp.List [str]:

"""Returns all values ​​from the square by pos
>>> grid = read_sudoku('puzzle1.txt')
>>> get_block(grid, (0, 1))
['5', '3', '.', '6', '.', '.', '.', '9', '8']
>>> get_block(grid, (4, 7))
['.', '.', '3', '.', '.', '1', '.', '.', '6']
>>> get_block(grid, (8, 8))
['2', '8', '.', '.', '.', '5', '.', '7', '9']
"""
pass **???**


    grid = [
        ["5", "3", ".", ".", "7", ".", ".", ".", "."],
        ["6", ".", ".", "1", "9", "5", ".", ".", "."],
        [".", "9", "8", ".", ".", ".", ".", "6", "."],
        ["8", ".", ".", ".", "6", ".", ".", ".", "3"],
        ["4", ".", ".", "8", ".", "3", ".", ".", "1"],
        ["7", ".", ".", ".", "2", ".", ".", ".", "6"],
        [".", "6", ".", ".", ".", ".", "2", "8", "."],
        [".", ".", ".", "4", "1", "9", ".", ".", "5"],
        [".", ".", ".", ".", "8", ".", ".", "7", "9"],
    ]

您可以使用列表理解来获取您需要的网格行和列的子集:

def get_row(grid,pos):   return grid[pos[0]]

def get_col(grid,pos):   return [row[pos[1]] for row in grid]

def get_block(grid,pos):
    br = pos[0]//3*3  # first row of block
    bc = pos[1]//3*3  # first column of block
    return [ grid[r][c] for r in range(br,br+3) for c in range(bc,bc+3) ]