python输入多个数字后续操作_有效地确定后续数字范围中的数字是否在有序列表中. (在Python中)...
對于范圍的每個邊界,您可以使用
binary-search兩次(使用
bisect.bisect_left()).
如果返回的索引相同,則沒有交集(返回None).
如果不是,則返回start_index處的元素(其中start_index是您的范圍開始時獲得的索引).
這是代碼:
import bisect
def intersect_range(lst, start, stop):
start_i = bisect.bisect_left(lst, start)
stop_i = bisect.bisect_left(lst, stop)
if start_i == stop_i:
return None
else:
return lst[start_i]
intersect_range([1,2,3,7,8,10,15], 5, 10)
=> 7
intersect_range([1,2,3,7,8,10,15], 5, 6)
=> None
intersect_range([1,2,3,7,8,10,15], 15,30)
=> 15
intersect_range([1,2,3,7,8,10,15], 0,1) # "stop" is excluded from range
=> None
由于您執行了兩次二進制搜索,因此復雜度為O(logN),其中N是列表的長度.
編輯:
還有一個稍快的替代方案,即二進制搜索范圍的開始,然后檢查lst [start_index]是否在范圍內(start< = lst [start_i]< stop).這將logN操作的數量從兩個減少到一個.代碼如下所示:
def intersect_range(lst, start, stop):
start_i = bisect.bisect_left(lst, start)
if start <= lst[start_i] < stop:
return lst[start_i]
else:
return None
總結
以上是生活随笔為你收集整理的python输入多个数字后续操作_有效地确定后续数字范围中的数字是否在有序列表中. (在Python中)...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: jvm 堆外内存_NIO效率高的原理之零
- 下一篇: python 爬取svg数据_pytho