I have to complete the code that solves the sudoku. The problem is as follows, you need to write the code that outputs the coordinates of the row / column / square. By condition, "pos" is specified, with the help of which coordinates are transmitted. I tried to write in different ways, but not quit. I ask for help! Below is the code with comments.
pos = (0, 0)
row, col = pos
Correct code for 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"],
]
You can use list comprehension to get the subset of grid rows and columns that you need:
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) ]