我正在尝试使用参数(tuple,int)创建二进制搜索(迭代和递归)。我真的想更多地理解它,因为我认为我在逻辑上理解代码,但显然不是。
迭代代码(isMemberI)在一半的时间给我正确的结果,然后随机不正确,所以我不知道是什么导致了这个。我有时没有错误,只是错误的答案。
递归代码有时会给我错误,然后可能会有1/4的测试用例。当我尝试以下操作时,我收到了这些错误:
>>> isMemberR((1, 2, 3, 3, 4), 4
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
isMemberR((1, 2, 3, 3, 4), 4)
File "/Users/alyssakelley/Documents/p93_binsearch.py", line 127, in isMemberR
return isMemberR(aseq[midpoint + 1], target)
File "/Users/alyssakelley/Documents/p93_binsearch.py", line 117, in isMemberR
if len(aseq) == 0:
TypeError: object of type 'int' has no len()
>>> isMemberR('aeiou', 'y')
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
isMemberR('aeiou', 'y')
File "/Users/alyssakelley/Documents/p93_binsearch.py", line 127, in isMemberR
return isMemberR(aseq[midpoint + 1], target)
File "/Users/alyssakelley/Documents/p93_binsearch.py", line 127, in isMemberR
return isMemberR(aseq[midpoint + 1], target)
IndexError: string index out of range
>>> isMemberR((1, 3, 5, 7), 4)
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
isMemberR((1, 3, 5, 7), 4)
File "/Users/alyssakelley/Documents/p93_binsearch.py", line 125, in isMemberR
return isMemberR(aseq[:midpoint], target)
File "/Users/alyssakelley/Documents/p93_binsearch.py", line 127, in isMemberR
return isMemberR(aseq[midpoint + 1], target)
IndexError: tuple index out of range
这是我的代码:
def isMemberI(aseq, target):
first = 0
last = len(aseq) - 1
found = False
while first < last:
midpoint = (first + last) // 2
if aseq[midpoint] == target:
found = True
else:
if target < aseq[midpoint]:
last = midpoint - 1
else:
first = midpoint + 1
return found
def isMemberR(aseq, target):
if len(aseq) == 0:
return False
else:
midpoint = len(aseq) // 2
if aseq[midpoint] == target:
return True
else:
if target < aseq[midpoint]:
return isMemberR(aseq[:midpoint], target)
else:
return isMemberR(aseq[midpoint + 1], target)
我正在尝试的测试用例和结果我 EXPECT :
>>> isMemberI((1, 2, 3, 3, 4), 4)
True
>>> isMemberI((1, 2, 3, 3, 4), 2)
True
>>> isMemberI('aeiou', 'i')
True
>>> isMemberI('aeiou', 'y')
False
>>> isMemberI((1, 3, 5, 7), 4)
False
>>> isMemberI((23, 24, 25, 26, 27), 5)
False
>>> isMemberI((0, 1, 4, 5, 6, 8), 4)
True
>>> isMemberI((0, 1, 2, 3, 4, 5, 6), 3)
True
>>> isMemberI((1, 3), 1)
True
>>> isMemberI((2, 10), 10)
True
>>> isMemberI((99, 100), 101)
False
>>> isMemberI((42,), 42)
True
>>> isMemberI((43,), 44)
False
>>> isMemberI((), 99)
False
'''
答案 0 :(得分:1)
这里最后一个函数调用是传递索引midpoint+1
而不是元组的值。
错误说明
IndexError :元组索引超出范围,当元组的len为1且midpoint+1
为1
且超出范围时会发生这种情况因为只有一个元素
TypeError :'int'类型的对象没有len(),那就是当int
作为第一个争论传递给{{1 }}
isMemberR