数独求解器运行报错:切片索引必须为整数或None等合法类型
The error you're hitting comes down to using floating-point numbers as slice indices in your _check_box method—let's break this down and fix it:
Root Cause
In Python 3, the / operator returns a float even when dividing integers. So when you calculate rc = (row/3)*3 and cc = (col/3)*3, results like 3.0 or 6.0 end up being passed as slice indices to your numpy array. Numpy requires integer indices for slicing, hence the TypeError: slice indices must be integers....
The Fix: Switch to Integer Division
Replace the / operator with // (integer division) in the _check_box method. This ensures you always get an integer result:
def _check_box(self, digit, row, col): rc = (row // 3) * 3 cc = (col // 3) * 3 return digit not in self.grid[rc:rc+3, cc:cc+3]
Quick Additional Improvement
In your solve method, raising a raw string isn't best practice. Instead, raise a proper exception type like ValueError for better error handling:
def solve(self): if self._solve(): return self.grid raise ValueError("Sudoku cannot be solved")
Why This Works
Integer division (//) truncates any decimal part, so it correctly maps rows/columns to their 3x3 box boundaries:
- Rows 0-2 →
row//3 = 0→ box starts at row 0 - Rows 3-5 →
row//3 =1→ box starts at row3 - Rows6-8 →
row//3=2→ box starts at row6
This fixes the slicing error and lets your backtracking algorithm run as intended to solve the sudoku grid.
内容的提问来源于stack exchange,提问作者erkevarol

