牛骨文教育服务平台(让学习变的简单)
博文笔记

Python中bisect模块用法,及实现方式

创建时间:2015-09-28 投稿人: 浏览次数:996
#bisect用法:
import bisect
bisect.bisect_left(t,x) #在T列表中查找x,若存在,返回x左侧位置
bisect.bisect_right(t,x)
bisect.insort_left(t,x) #在T列表中查找X,若存在,插入x左侧;
bisect.insort_right(t,x)


下面是其实现的方法,实际是二分法:

def binary_search(t,x):
    temp = t;
    temp.sort();
    low = 0;
    mid = 0;
    high = len(temp)-1;
    while low < high:
        mid = (low+high)/2;
        if x<t[mid]:
            high = mid-1;
        elif x>t[mid]:
            low = mid+1;
        else:
            return mid-1; #是否等价与bisect_left;


阅读更多
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。