search first key

🏠
 1 def first_of_k(A, k, l=0, r=-1):
 2     if r == -1:
 3         r = len(A)-1
 4     m = (l + r) // 2
 5     if A[m] == k:
 6         if (m > 0 and A[m-1] != k) or m == 0:
 7             return m
 8         return first_of_k(A, k, l, r=m-1)
 9     elif A[m] < k:
10         return first_of_k(A, k, l=m+1, r=r)
11     else:
12         return first_of_k(A, k, l, r=m-1)
13 
14 res = first_of_k([-10, -5, 24, 24, 46, 46, 64, 64, 64, 180], 64)
15 print(res)

Using bisect

1 import bisect
2 
3 def search_first_of_k_pythonic(A, k):
4     i = bisect.bisect_left(A, k)
5     return i if i < len(A) and A[i] == k else -1
6 
7 search_first_of_k([-10, -5, 24, 24, 46, 46, 64, 64, 64, 180], 64)