如何解决为什么当元素不在列表中时我的二进制搜索功能不会停止?
我具有以下二进制搜索功能:
def in_bisect(sorted_list,target):
temp = sorted_list[:]
low = 0
mid = (len(temp)-1) // 2
high = len(temp)-1
count = 0
if target > temp[high] or target < temp[low]:
return False
while True:
mid = len(temp) // 2
count += 1
if target == temp[mid]:
print("Target found in %d steps " % count)
return True
elif target > temp[mid]:
low = mid
temp = temp[low:]
elif target < temp[mid]:
high = mid
temp = temp[:high]
return False
当我在给定单词列表中寻找元素时,它可以正常工作。但是,当我测试不在列表中的单词时,循环将变为无限!!
我已经用113k +字母排序的单词列表对其进行了测试,它非常有效(或者至少我想以这种方式),它最多可以17个步骤找到目标。
这是我做过的测试:
if __name__ == '__main__':
fin = open('words.txt')
a = []
for line in fin:
a.append(line.strip())
print(in_bisect(a,'longsome'))
'longsome'
是words.txt
文件中的一个词,如果我将其更改为'blahblah'
,则循环永远存在。
如果没有匹配项,我希望它立即返回False
。
另外,感谢您在此过程中提出的任何改进建议。
解决方法
while循环无法中断,因此直到我们超出了要搜索的范围,我们才继续,否则,我们中断。另外,low = mid + 1
是必需的,否则列表大小将无法正确减小。与high
相同。
def in_bisect(sorted_list,target):
temp = sorted_list[:]
low = 0
mid = (len(temp)-1) // 2
high = len(temp)-1
count = 0
if target > temp[high] or target < temp[low]:
return False
while True:
if len (temp) == 0:
break
mid = len(temp) // 2
count += 1
if target == temp[mid]:
print("Target found in %d steps " % count)
return True
elif target > temp[mid]:
low = mid + 1
temp = temp[low:]
elif target < temp[mid]:
high = mid - 1
temp = temp[:high + 1]
return False
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。