In [31]:
from typing import List
import numpy as np
In [40]:
def find_index_equals_val(lst: List[int], b: int, e: int, depth: int=0) -> bool:
assert sorted(lst) == lst
assert len(set(lst)) == len(lst)
m = b + (e - b) // 2
last = e - b == 1
if m == lst[m]:
print(f'depth: {depth}, log2(n): {np.log2(len(lst))}')
return True
else:
if lst[m] < m:
# go right
if last:
print(f'depth: {depth}, log2(n): {np.log2(len(lst))}')
return lst[e] == e
return find_index_equals_val(lst, m, e, depth + 1)
else:
# go left
if last:
print(f'depth: {depth}, log2(n): {np.log2(len(lst))}')
return lst[b] == b
return find_index_equals_val(lst, b, m, depth + 1)
In [41]:
find_index_equals_val([1, 2, 3], 0, 2) == False
Out[41]:
In [42]:
find_index_equals_val([0, 1, 3], 0, 2) == True
Out[42]:
In [43]:
find_index_equals_val([-1, 1, 2, 3], 0, 3) == True
Out[43]:
In [44]:
find_index_equals_val([-1, 0, 2, 3], 0, 3) == True
Out[44]:
In [48]:
len(list(range(-1, 10)) + list(range(100, 200)))
Out[48]:
In [50]:
find_index_equals_val(list(range(-1, 10)) + list(range(100, 200)), 0, 110) == False
Out[50]:
In [59]:
find_index_equals_val(list(range(-1, 10)) + [11] + list(range(1000, 2000)), 0, 1010) == True
Out[59]: