You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

数独求解器运行报错:切片索引必须为整数或None等合法类型

Fixing the TypeError in Your Sudoku Solver

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:11:02