Searching a sorted list?
python, search, sorting
Solution
Python:
import bisect
def find_in_sorted_list(elem, sorted_list):
# https://docs.python.org/3/library/bisect.html
'Locate the leftmost value exactly equal to x'
i = bisect.bisect_left(sorted_list, elem)
if i != len(sorted_list) and sorted_list[i] == elem:
return i
return -1
def in_sorted_list(elem, sorted_list):
i = bisect.bisect_left(sorted_list, elem)
return i != len(sorted_list) and sorted_list[i] == elem
L = ["aaa", "bcd", "hello", "world", "zzz"]
print(find_in_sorted_list("hello", L)) # 2
print(find_in_sorted_list("hellu", L)) # -1
print(in_sorted_list("hellu", L)) # False
Problem
What is a Pythonic way to search or manipulate sorted sequence?