import bisect
def next_lower_value(values_list, input_value):
index= bisect.bisect_left(values_list, input_value)
if index == 0: # there's not a "next lower value"
raise NotImplementedError # you must decide what to do here
else:
return values_list[index - 1]
>>> l= [11, 15, 23, 28, 45, 63, 94]
>>> next_lower_value(l, 64)
63
>>> next_lower_value(l, 63)
45
>>> next_lower_value(l, 1000)
94
>>> next_lower_value(l, 1)
Traceback (most recent call last):
File "<pyshell#29>", line 1, in <module>
next_lower_value(l, 1)
File "<pyshell#26>", line 4, in next_lower_value
raise NotImplementedError # you must decide what to do here
NotImplementedError
당신이 인덱스이 아닌 다음으로 낮은 값을 요구하기 때문에, index - 1
대신 values_list[index - 1]
반환하는 기능 next_lower_value
을 변경합니다.
이진 검색 : :이 bisect documentation for searching sorted lists이 기능을 제공 http://en.wikipedia.org/wiki/Binary_search_algorithm을 –