Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Copia questo prompt nella nostra Console per sviluppatori per provarlo tu stesso!
| Content | |
|---|---|
| System | Il tuo compito è creare funzioni Python basate sulle richieste in linguaggio naturale fornite. Le richieste descriveranno la funzionalità desiderata della funzione, inclusi i parametri di input e il valore di ritorno previsto. Implementa le funzioni secondo le specifiche fornite, assicurandoti che gestiscano i casi limite, eseguano le convalide necessarie e seguano le migliori pratiche per la programmazione Python. Includi commenti appropriati nel codice per spiegare la logica e aiutare altri sviluppatori a comprendere l'implementazione. |
| User | Voglio una funzione che possa risolvere un puzzle Sudoku. La funzione dovrebbe prendere una griglia Sudoku 9x9 come input, dove le celle vuote sono rappresentate dal valore 0. La funzione dovrebbe risolvere il puzzle utilizzando un algoritmo di backtracking e restituire la griglia risolta. Se il puzzle è irrisolvibile, dovrebbe restituire None. La funzione dovrebbe anche convalidare la griglia di input per assicurarsi che sia un puzzle Sudoku valido. |
def solve_sudoku(grid):
def is_valid(row, col, num):
# Check if the number is valid in the current row and column
for i in range(9):
if grid[row][i] == num or grid[i][col] == num:
return False
# Check if the number is valid in the current 3x3 subgrid
start_row, start_col = (row // 3) * 3, (col // 3) * 3
for i in range(3):
for j in range(3):
if grid[start_row + i][start_col + j] == num:
return False
return True
def backtrack(row, col):
# If we have filled all cells, the puzzle is solved
if row == 9:
return True
# Move to the next row if we have reached the end of the current row
if col == 9:
return backtrack(row + 1, 0)
# If the current cell is already filled, move to the next cell
if grid[row][col] != 0:
return backtrack(row, col + 1)
# Try filling the current cell with numbers from 1 to 9
for num in range(1, 10):
if is_valid(row, col, num):
grid[row][col] = num
if backtrack(row, col + 1):
return True
grid[row][col] = 0
# If no valid number is found, backtrack
return False
# Validate the input grid
if not all(len(row) == 9 and all(0 <= cell <= 9 for cell in row) for row in grid):
return None
# Start the backtracking algorithm
if backtrack(0, 0):
return grid
else:
return None
Was this page helpful?