bisect模块跟踪列表,保持其排序,而不必在每次插入元素时求助。您需要实现的方法只需要在排序列表中搜索。
def bisect(sortedlist,targetvalue,firstindex=0,lastindex=None):
if(len(sortedlist)==0):
return None
if(len(sortedlist)==1):
if(sortedlist[0]==targetvalue):
return firstindex
else:
return None
center = int(round(len(sortedlist)/2))
if(sortedlist[center]==targetvalue):
return firstindex+center
if(targetvalue>sortedlist[center]):
return bisect(sortedlist[center+1:lastindex],targetvalue,center+1,lastindex)
else:
return bisect(sortedlist[0:center],targetvalue,firstindex,center-1)这基本上是二进制搜索。
传递索引以跟踪递归循环中进一步调用的原始列表的索引。