【问题标题】:Python 3 binary search a sorted variable (list of numbers)Python 3二进制搜索排序变量(数字列表)
【发布时间】: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


    【解决方案1】:

    sys.argv 是一个列表,其中包含用于调用 python 进程的命令行参数。 sys.argv[0] 是脚本的名称,sys.arv[1:] 是其余参数。像这样访问它:

    def binary_search(needle, haystack):
        print('binary_search(): needle = {}, haystack = {}'.format(needle, haystack))
        # your implementation here
    
    if __name__ == '__main__':
        import sys
    
        if len(sys.argv) > 2:
            needle = sys.argv[1]
            haystack = sys.argv[2:]
            binary_search(needle, haystack)
        else:
            print('Usage: {} needle haystack...'.format(sys.argv[0]))
    

    如果您需要先对大海捞针进行排序,请使用sorted()

    binary_search(needle, sorted(haystack))
    

    但是,首先排序没有什么意义,因为它具有 O(n log n) 时间复杂度,而线性搜索只有 O(n) 时间复杂度.因此,如果输入未排序,最好只通过迭代列表进行搜索,直到找到目标。


    最后,您可能需要将输入转换为数值才能进行搜索。您可以为此使用int()

            needle = int(sys.argv[1])
            haystack = [int(s) for s in sys.argv[2:]]
    

    【讨论】:

    • 您好,谢谢您的回复!你在这里帮了我很多,但是,当我现在运行它时,它说: typeError: list indices must be integers or slices, not float
    • 并且错误与以下行有关: binary_search(int(needle), sorted(int(s) for s in haystack)) 和行: if haystack[mid] == needle:
    • @mhawke timsort(Python 中的默认排序算法)只有 O(n log n) 复杂度在最坏的情况下 - 在已经排序的数据上它是线性的。
    • 我认为仍然有问题:如果 haystack[mid] == needle: ........ 它说列表索引必须是整数或切片,而不是浮点数,我将 mid 定义为由 2 定义的东西,所以它可能会给出错误,因为 mid 可以是 0.5?我尝试使用 int(mid) 但这不起作用,因为 mid 已经是一个 int...
    • @RubenWeijers 我假设您使用的是 Python 3 - 如果是这样,您想要 mid = round((first + last) / 2)
    【解决方案2】:

    二进制搜索是标准库的一部分。以下是如何使用它来解决您的问题:

    import sys
    import bisect
    
    argv = [int(_) for _ in sys.argv[1:]]
    x = argv.pop(0)
    i = bisect.bisect_left(argv, x)
    print("Found:", i != len(argv) and argv[i] == x)
    

    另外,这个问题只有在输入列表已经排序的情况下才有意义。如果不是,只需使用x in argv,它是线性的(对列表进行排序是线性的)。

    【讨论】:

      猜你喜欢
      • 2015-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-19
      相关资源
      最近更新 更多