您的位置:首页 > 编程语言 > Python开发

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

2015-09-28 22:24 706 查看
#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;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: