这是代码,我正在尝试使用类内部的方法获取二进制搜索结果。该类具有更多功能,但只有该功能给出错误的输出(None
以整数表示)。的if
15部分从行号10引起问题。
class Solution:
def getNum(self, nums, x):
L_nums = len(nums)
j = self.binary_search( nums, 0, L_nums-1, x)
print("j=",j)
def binary_search(self, nums, start, end, x):
print("BS called start=>", start,"end=>", end,"x=>", x)
if end==start:
if nums[end]==x:
return end
else:
print("called else and returing -1")
return -1
i = (end-start)//2 + start
print("i=",i)
if x==nums[i]:
return i
elif x>nums[i]:
self.binary_search(nums, i+1, end, x)
else:
self.binary_search(nums, start, i-1, x)
sol = Solution()
sol.getNum([1,3,5,7,9],1)
输出:此处j
应为0,以代替返回None
BS called start=> 0 end=> 4 x=> 1
i= 2
BS called start=> 0 end=> 1 x=> 1
i= 0
j= None
对您的问题的简短回答:在原始21,23中包括“返回”。
elif x>nums[i]:
return self.binary_search(nums, i+1, end, x)
else:
return self.binary_search(nums, start, i-1, x)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句