Skip to content Skip to sidebar Skip to footer

How To Find The Smallest Closest Number In A List In Python

I want to know how can I find the smallest closest number in a list to a given number. For example: number = 20 list_of_numbers = [4, 9, 15, 25] I tried this: min(list_of_number

Solution 1:

You could make the key also contain the number itself and use that for breaking ties:

min(list_of_numbers, key=lambda x: (abs(x - number), x))

Your behavior is strange, though. It might be a bug. You might be able to work around it by using sorted, which is stable:

sorted(list_of_numbers, key=lambda x: abs(x - number))[0]

Solution 2:

Add the number from the list of numbers to the key, so it's taken into account.

min(list_of_numbers, key=lambda x: (abs(x - number), x))

Also if you want the first number from the list which matches the requirement, add the index to the key:

min(enumerate(list_of_numbers), key=lambda ix: (abs(ix[1] - number), ix[0]))[1]

Though this would only be needed under Python 2, because Python 3 guarantees that:

If multiple items are minimal, the function returns the first one encountered. This is consistent with other sort-stability preserving tools such as sorted(iterable, key=keyfunc)[0] and heapq.nsmallest(1, iterable, key=keyfunc).

Solution 3:

Instead of this

min(list_of_numbers, key=lambda x:abs(x-number))
 

Try this :

number = 20
list_of_numbers = [4, 9, 15, 25]
list_of_numbers.sort(reverse=True)
min(list_of_numbers,key=lambda x : x - number > 0 )

Post a Comment for "How To Find The Smallest Closest Number In A List In Python"