How can I round the next number in a list?

Viewed 114

Let me tell you what I mean. Let's say I have a list that consists of 75, 250, 525, and 900. And let's say a random number, 95. How can I round 95 to 250?

So far, I have only made it, so it rounds to the closest number but not the next integer.

def closest(lst, K): 
      
    return lst[min(range(len(lst)), key = lambda i: abs(lst[i]-K))] 
      
lst = [75, 250, 525, 900] 
K = 95
print(closest(lst, K))
3 Answers

If your list is always sorted, you can use bisect:

import bisect 
lst = [75, 250, 525, 900] 
k=95

>>> lst[bisect.bisect_right(lst, k)]
250

You will need to decide what you want to return when k is larger than all numbers in lst As currently written, if k>=900 that would be an index error. Easily fixed with try ... except but you need to specify what the 'right' answer is in that case.

Bisect would be the best choice for large lists since it is written in C and super fast.

Alternatively, you can use the next built-in function:

>>> next((e for e in lst if e>k), default_if_not_found)
250

Same comment: you would need to define a default value if e>k cannot be found.

I'm old school. I'd prefer something with a few more lines that anyone who sees the code can understand:

def closest(lst, n):
    for i in lst:
        if i > K:
            return i
    return None

K = 95
lst = [75, 250, 525, 900]

print(closest(lst, K))

As long as the list is guaranteed to be sorted this should work, returning None if k is greater than all elements in l.

def closest(l, k):
    for i in l:
        if k < i:
            return i
    return None
      
res = closest([75, 250, 525, 900] , 95)
Related