Reputation: 121
I have 15 numbers,
[1, 5, 10, 20, 30, 50, 70, 100, 150, 200, 500, 1000, 2000, 5000, 10000]
I have people entering the quantity and what I want is it to round to the lowest number. hence if someone enters 36
it will round to 30
.
Upvotes: 0
Views: 197
Reputation: 86188
Here is a recursive solution. It should be O(log n); it relies on the fact that the list is sorted.
L = [1, 5, 10, 20, 30, 50, 70, 100, 150, 200, 500, 1000, 2000, 5000, 10000]
def roundit(x,n):
if len(x) == 1:
return x[0]
elif x[len(x)/2] > n:
return roundit(x[0:len(x)/2],n)
else:
return roundit(x[len(x)/2 :],n)
Result:
>>> roundit(L,36)
30
>>> roundit(L,77)
70
>>> roundit(L,150)
150
Upvotes: 2
Reputation: 212885
bisect
will do it in O(log N):
>>> import bisect
>>> L = [1, 5, 10, 20, 30, 50, 70, 100, 150, 200, 500, 1000, 2000, 5000, 10000]
>>> L[bisect.bisect(L, 36) - 1]
30
or with pure python and O(N):
>>> L = [1, 5, 10, 20, 30, 50, 70, 100, 150, 200, 500, 1000, 2000, 5000, 10000]
>>> next(elem for elem in reversed(L) if elem <= 36)
30
assumed the L
list is sorted. Otherwise L.sort()
it before.
Upvotes: 7
Reputation: 362756
With pure python:
>>> numbers = [1, 5, 10, 20, 30, 50, 70, 100, 150, 200, 500, 1000, 2000, 5000, 10000]
>>> x = 36
>>> max(n for n in numbers if n <= x)
30
note: Does not rely on numbers list being sorted.
Upvotes: 7