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

LeetCode刷题时Solution类内的binary_search函数为何提示未定义

错误原因&修复方案

1. 核心报错原因

你遇到的NameError和未编写__init__构造方法完全无关,是Python类的实例方法调用规则问题:

  • 在Python类中定义的、第一个参数带self的方法属于实例方法,在类内部其他方法调用该方法时,必须添加self.前缀,否则Python会将其识别为全局函数去查找,自然找不到你定义在类内部的binary_search方法。
  • 你之前本地去掉class Solution外层后能正常运行,就是因为此时binary_search是全局定义的函数,直接调用不会有问题。
  • 你需要修改两处调用位置:
    • 递归调用return(binary_search(...))改为return self.binary_search(...)
    • searchInsert方法里的output = binary_search(...)改为output = self.binary_search(...)

2. 额外逻辑优化建议

你的代码里同时混用了while循环和递归逻辑,属于冗余写法:每次条件判断后直接return了递归调用结果,循环体永远只会执行一次,完全可以把外层的while end >= start:判断改成普通的if判断即可,不影响运行逻辑但可读性更好。

修正后的可运行代码

class Solution(object):
    def binary_search(self, nums, target, start, middle, end):
        if nums[middle] == target:
            return middle
        # 冗余while改为if即可
        if end >= start:
            if nums[middle] > target: 
                end = middle - 1 
                middle = (start + end) // 2
                return self.binary_search(nums, target, start, middle, end)
            elif nums[middle] < target:
                start = middle + 1
                middle = (start + end) // 2
                return self.binary_search(nums, target, start, middle, end)
        return middle + 1
    
    def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        start = 0
        end = len(nums)-1
        middle = end // 2
        output = self.binary_search(nums, target, start, middle, end)
        return output

内容的提问来源于stack exchange,提问作者Soccerball123

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 00:09:04