【问题标题】:Python - Binary search to find elements of a list that match the index?Python - 二进制搜索以查找与索引匹配的列表元素?
【发布时间】:2020-07-08 21:48:07
【问题描述】:

所以我想使用二进制搜索来搜索列表,并找到列表中具有与索引号匹配的值的元素。例如,如果我的列表在索引 2 处包含 2,我想打印该值。它也必须与多个值一起使用。这是我到目前为止的二进制搜索:

alist=[4,5,7,9,13,45,34,58,99,125,145]
key=145
"""Search key in alist[start... end - 1]."""
start = 0
end = len(alist)
while start < end:
    mid = (start + end)//2
    if alist[mid] > key:  # this is where we check if the guess is bigger than the key
            end = mid
    elif alist[mid] < key:
            start = mid + 1
    elif alist[mid] == key:
                print (f"you searched for {alist[mid]} and we found it in the index number {alist.index(125)} of the list")
                break
else:
    print ("Not Found!")

这仅适用于密钥。我是 python 新手,想知道如何实现它。

【问题讨论】:

  • 为什么要为此使用二分搜索?听起来更像是您想遍历列表并单独检查每个元素。
  • 但是貌似列表是排序的,所以可以通过二分查找降低复杂度@a_guest
  • @yatu 我认为二进制搜索不会有帮助。首先,列表没有排序。即使是 OP 也不想定位单个元素,而是根据它们在列表中的位置满足某些条件的任意数量的元素。
  • 是的,如果列表没有排序确实二进制搜索没有意义,我虽然它是但只是注意到那些不是的 2 个元素。但是,如果它们已排序,则如果您看到该值已经超过索引,则可以轻松丢弃列表的大部分内容,例如,您无需再遍历其中一侧@a_guest
  • @yatu 我认为这不是真的。如果列表已排序(并且仅包含正值),那么您需要允许重复以使问题有意义(否则它是微不足道的,从头开始直到第一个元素违反条件)。然后有三个选项:a = [0, 1, 2, 3, 4]; b = [0, 1, 1, 3, 4]; c = [0, 1, 3, 3, 4]。二分查找从中间开始,索引为 2。这三个列表仅在该元素上有所不同。它们代表所有可能的情况,即a[2] == 2, b[2] &lt; 2, c[2] &gt; 2 由于其余部分相同,因此无法得出任何结论。

标签: python python-3.x list binary-search


【解决方案1】:

如果我对您的理解正确,我认为这应该适用于您的打印声明:

print("you searched for {} and we found it in the index number {} of the list".format(key, mid))

如果你只想在索引与值相同时打印它,你可以添加一个 if 语句:

if key == mid:
    print("you searched for {} and we found it in the index number {} of the list".format(key, mid))

这能回答你的问题吗?

【讨论】:

  • 我想在没有键的情况下搜索列表。我只想找到与其值的索引号具有相同值的元素。我可以暴力破解它,但我想使用二进制搜索。蛮力将是一个带有 if 语句的 for 循环,例如 if index == value, print value
  • @user2429456 为什么要使用二分搜索? 1)它似乎不适合你的问题,2)它只适用于排序列表,但你的数据没有排序。如果是这样,您需要允许重复才能满足至少一个元素的此条件(alist = list(range(N)) 的简单情况除外)。您能否更具体地说明您的输入数据。
【解决方案2】:

如果我正确理解您的问题,您想找到与其索引号具有相同值的元素,那么您必须遍历列表并使用条件打印元素 print([i for i in alist if i==alist.index(i)])

【讨论】:

    猜你喜欢
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 2021-05-19
    • 1970-01-01
    • 1970-01-01
    • 2017-09-12
    • 2013-03-28
    • 1970-01-01
    相关资源
    最近更新 更多