Reputation: 105
I have a list in my python script [79.99, 82.99, 83.99, 84.99, 85.99, 86.99, 87.99, 88.99, 89.99]
and an ever increasing number in a loop. I want to create a condition so when this number reaches a number between one of those ranges, it will take the lower number of the range and process it.
For example while (i!=10000): i=+1
and if i between range(above_range): print(low_Range_number)
if the number would be 81.99, it would pick 79.99 if the number would be 84.23, it would pick 83.99
Upvotes: 0
Views: 7146
Reputation: 54203
This is what the bisect
stdlib module is made for.
import bisect
entries = [79.99, 82.99, 83.99, 84.99, 85.99, 86.99, 87.99, 88.99, 89.99]
x = 81.5
def get_lower_bound(haystack, needle):
"""Get lower bound between two numbers in a sorted list
If needle is lower than the lower bound, or higher than the higher bound of
the sorted list, then raise ValueError.
>>> get_lower_bound([1,2,3], 1.5)
1
>>> get_lower_bound([1,2,3], 2)
2
>>> get_lower_bound([1,2,3], 0)
Traceback (most recent call last):
...
ValueError: 0 is out of bounds of [1, 2, 3]
>>> get_lower_bound([1,2,3], 4)
Traceback (most recent call last):
...
ValueError: 4 is out of bounds of [1, 2, 3]
"""
idx = bisect.bisect(haystack, needle)
if 0 < idx < len(haystack):
return haystack[idx-1]
else:
raise ValueError(f"{needle} is out of bounds of {haystack}")
Upvotes: 8
Reputation: 41
You add your value to the list, sort it, find your value's index and then ask for the previous one (finally remove your value):
a = [79.99, 82.99, 83.99, 84.99, 85.99, 86.99, 87.99, 88.99, 89.99]
limit = len(a)
for i in range(0, 10000):
a.append(i)
a.sort()
ix = a.index(i)
if ix > 0 and ix <= limit: print(a[ix-1])
a.remove(i)
Upvotes: 2
Reputation: 2882
Your list seems to be sorted, so:
def lower_bound(x, l):
if not l or l[0] > x:
return
for i, y in enumerate(l):
if y > x:
return l[i - 1]
If nothing satisfies your search, it'll return None
. If not sorted, call l.sort()
before you do.
Upvotes: 4