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

Python 查找有序列表中指定元素所在位置

2015-01-19 15:15 597 查看
# Modified version of the binary search that returns the index within
# a sorted sequence indicating where the target should be located
def findSortedPosition(theList, target):
low = 0
high = len(theList) - 1
while low <= high:
mid = (high + low) // 2
if theList[mid] == target:
return mid
elif target < theList[mid]:
high = mid -1
else:
low = mid + 1
return low


In [3]: theList = [1,2,3,4,5,6]
In [9]: target = 1
Out[9]: 1
In [8]: findSortedPosition(theList, target)
Out[8]: 0
In [10]: target = 7
In [11]: findSortedPosition(theList, target)
Out[11]: 6
In [12]: findSortedPosition(theList, 2.5)
Out[12]: 2
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐