Home > front end >  How do I find the closest number in a list that is greater than my number?
How do I find the closest number in a list that is greater than my number?

Time:12-04

I want to get the closest number (or the index of it) in a list that is greater than a given number. The list:

lst=[1,2,5]

My number:

num=3

If I use: min(lst, key=lambda x:abs(x-num)) it will give 2 but I want it to give me 5

CodePudding user response:

You need to consider numbers greater than num:

output, index = min((i, idx) for idx, i in enumerate(lst) if i>num)

CodePudding user response:

You could write an actual loop to do it:

closest_greater = None
for item in lst:
    if item > num and (closest_greater is None or item < closest_greater):
        closest_greater = item

gives closest_greater = 5

Alternatively, you could give the min() function a generator expression that includes only elements that are greater than num

min(i for i in lst if i > num)

CodePudding user response:

Would you like to use a binary sort? In my tests, this is slightly faster.

import time
from bisect import bisect


def timer(func):
    def function_timer(*args, **kwargs):
        start = time.time()
        func(*args, **kwargs)
        print "The runtime took {} seconds to complete".format(round(time.time() - start, 2))

    return function_timer


test_list = [1, 7, 5, 6, 3, 8]
k = 3

@timer
def t1():
    for x in range(1000000):
        test_list[bisect(test_list, k)]


@timer
def t2():
    for x in range(1000000):
        min((i, idx) for idx, i in enumerate(test_list) if i > k)

yields

The runtime took 0.22 seconds to complete
The runtime took 0.94 seconds to complete
  • Related