【发布时间】:2018-08-31 05:34:19
【问题描述】:
你好 :) 我正在编写一个通过排序列表使用二进制搜索的程序。它应该按如下方式工作:python find.py 3 1 2 3
程序应该在数字 1 2 和 3 中寻找 3
如果它在 1 2 和 3 中,它应该返回 true 并打印找到的针, 如果它不在 1 2 和 3 if 应该返回 false 并且 print 没有找到....
def binary_search(needle, haystack):
first = 0
last = len(haystack) - 1
itemlist = str(input(haystack))
sorted(itemlist)
while first <= last:
mid = (first + last) / 2
if itemlist[mid] == needle :
print("Found the needle in the haystack")
return True
elif needle < itemlist[mid]:
last = mid - 1
else:
first = mid + 1
if not True:
print("Did not find the needle in the haystack")
return False
所以我尝试实现一个标准的二进制搜索算法,但是我遇到的每个版本都不会将第一个数字作为您需要在以下所有数字中搜索的项目... 所以我的问题是,如何将第一个变量设置为“项目”,然后将所有内容设置为可能包含或不包含项目的列表?
我还需要对 x 长度的列表进行排序,所以我尝试了 sorted 函数,但是由于列表可以是任意长度,我需要对变量进行排序吗?我有点卡在那里......关于这些主题的任何提示?
【问题讨论】:
标签: python python-3.x sorting binary-search