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
相关产品推荐
相关产品推荐

