Home  >  Article  >  Backend Development  >  How to Find the Closest Number in a List to a Given Value?

How to Find the Closest Number in a List to a Given Value?

Barbara Streisand
Barbara StreisandOriginal
2024-11-11 06:24:02725browse

How to Find the Closest Number in a List to a Given Value?

Finding the Closest Number in a List to a Given Value

Given a list of integers, you may need to determine which number is closest to a given value. This task can be tackled efficiently using the following methods:

Unsorted List:

If the input list is unsorted, you can utilize the built-in min() function with a key argument. This allows you to find the element with the minimum absolute difference from the target value.

>>> myList = [4, 1, 88, 44, 3]
>>> myNumber = 5
>>> min(myList, key=lambda x: abs(x - myNumber))
4

This method takes O(n) time, as it iterates through the entire list.

Sorted List:

Alternatively, if the list is already sorted or you're willing to sort it once, you can employ the bisection method. This technique uses binary search to locate the insertion point of the target value, effectively finding the closest element in O(log n) time. Here's an example implementation using Python's bisect module:

>>> from bisect import bisect_left
>>> myList = sorted([4, 1, 88, 44, 3])
>>> myNumber = 5
>>> bisect_left(myList, myNumber)
2
>>> myList[2]
4

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

Statement:
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