相关疑难解决方法(0)

在Python中,如何在排序列表中找到第一个值大于阈值的索引?

在Python中,如何在排序列表中找到第一个值大于阈值的索引?

我可以想到几种方法(线性搜索,手写二分法,......),但我正在寻找一种干净,合理有效的方法.由于它可能是一个非常常见的问题,我相信经验丰富的SOers可以提供帮助!

谢谢!

python algorithm search bisection

28
推荐指数
1
解决办法
2万
查看次数

Python二进制搜索类函数,用于查找排序列表中第一个大于特定值的数字

我正在尝试在Python中编写一个函数,它找到排序列表中的第一个数字,该数字大于我作为参数传递的特定值.我在网上找到了使用简单列表推导来实现这一目的的例子,但出于我的目的,我需要经常在大型列表上执行此操作,因此在线性时间内运行的搜索过于昂贵.

虽然我遇到了一些无法正常工作的边缘情况,但我在编写迭代二进制搜索类函数时遇到了麻烦.顺便说一下,该功能不需要处理列表中没有较大项目的情况.这是我现有的功能:

def findFirstLarger(num, sortedList):
    low = 0; 
    high = len(sortedList) - 1

    mid = -1
    while True:
        print("low: " + str(low) + "\t high: " + str(high))
        if (low > high):
            print("Ah geez, low is " + str(low) + " and high is " + str(high))
            return # debugging, don't want this to happen
        if low == high:
            return sortedList[low]
        else:
            mid = (low + high) / 2;
            if num == sortedList[mid]:
                return sortedList[mid]
            elif num > sortedList[mid]:
                low …
Run Code Online (Sandbox Code Playgroud)

python binary-search

3
推荐指数
1
解决办法
8386
查看次数

标签 统计

python ×2

algorithm ×1

binary-search ×1

bisection ×1

search ×1