Home > Backend Development > Python Tutorial > How to Find the Closest Number in a List of Integers?

How to Find the Closest Number in a List of Integers?

DDD
Release: 2024-11-09 05:11:01
Original
901 people have browsed it

How to Find the Closest Number in a List of Integers?

Finding the Closest Number to a Given Value in a List of Integers

Suppose we have a list of integers and want to determine which number is closest to a given value. We can employ various methods to achieve this.

Using min() Function for Unsorted Lists:

If we cannot guarantee that the list is sorted, we can leverage the built-in min() function. It selects the element with the minimum distance from the specified number using a key function.

>>> min(myList, key=lambda x:abs(x-myNumber))
4
Copy after login

This method efficiently finds the closest number in O(n) time complexity.

Using Bisection Method for Sorted Lists:

If the list is already sorted, or we are willing to sort it once, we can employ the bisection method. This method reduces the time complexity to O(log n). However, checking if the list is already sorted takes O(n), and sorting itself requires O(n log n).

>>> low, high = 0, len(myList) - 1
>>> while low <= high:
>>>     mid = (low + high) // 2
>>>     if myList[mid] == myNumber:
>>>         return myList[mid]
>>>     elif myList[mid] > myNumber:
>>>         high = mid - 1
>>>     else:
>>>         low = mid + 1
>>>     if low > high:
>>>         closest = myList[high] if abs(myList[high] - myNumber) < abs(myList[low] - myNumber) else myList[low]
>>>         return closest
Copy after login

By selecting the closest element, this method provides an optimal solution for sorted lists.

The above is the detailed content of How to Find the Closest Number in a List of Integers?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template