在大型排序列表中有效地找到数量最小的索引,该索引大于某个值

时间:2018-12-05 06:06:55

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

如果我有一长串排序的数字,并且我想找到大于某个值的最小元素的索引,那么有没有一种方法可以比对整个列表使用二进制搜索更有效地实现它?

例如:

import random
c = 0
x = [0 for x in range(50000)]

for n in range(50000):
    c += random.randint(1,100)
    x[n] = c

找到x中小于某个数字z的最大元素的位置的最有效方法是什么

我知道您已经可以:

import bisect
idx = bisect.bisect(x, z)

但是,假设此操作可以执行多次,那么还有比二进制搜索更有效的方法吗?由于列表的范围很大,因此创建所有可能整数的字典将占用过多内存。是否可以创建一个较小的列表(例如每5000个数字)并将其用于加快对较大列表的特定部分的查找?

1 个答案:

答案 0 :(得分:0)

您能尝试一下是否可以解决? 生成列表需要很长时间,但是报告结果似乎很快。

给出列表:

import random
limit = 50 # to set the number of elements
c = 0
x = [0 for x in range(limit)]

for n in range(limit):
    c += random.randint(1,100)
    x[n] = c
print(x)

由于它是一个有序列表,因此可以使用for循环来检索值:

z = 1600 # reference for lookup

res = ()
for i, n in enumerate(x):
  if n > z:
    res = (i, n)
    break

print (res) # this is the index and value of the elements that match the condition to break
print(x[res[0]-1]) # this is the element just before