I\'m trying to write a function in Python that finds the first number in a sorted list greater than a specific value that I pass in as an argument. I\'ve found examples onl
Have you tried the bisect module?
def find_ge(a, key):
'''Find smallest item greater-than or equal to key.
Raise ValueError if no such item exists.
If multiple keys are equal, return the leftmost.
'''
i = bisect_left(a, key)
if i == len(a):
raise ValueError('No item found with key at or above: %r' % (key,))
return a[i]
find_ge(somenumbers, 262139)
Your code is wrong that (1) low > high
is a valid termination case. (2) you should not stop at low == high
, e.g. it will return an incorrect index when num == 3
for your somenumbers
.
If you need the implementation without bisect function, you can try the following code:
def findFirstLargerOrEqual(num, sortedList):
'''Finds the smallest index in the sortedList
of the element which is greater-than or equal to num'''
slen = len(sortedList)
start = 0
while slen > 0:
m = start + slen//2
if sortedList[m] < num:
slen = slen - (m+1 - start)
start = m+1
continue
if start < m and sortedList[m-1] >= num:
slen = m - start
continue
return somenumbers[m]
raise ValueError('Not found')
somenumbers=[n*2 for n in range(131072)]
print(findFirstLargerOrEqual(262139, somenumbers)) #output: 262140