How do you find the closest number in a list to a given value?

DDD
Release: 2024-11-09 17:48:02
Original
608 people have browsed it

How do you 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 and a target number, the task is to find the number in the list that is closest to the target. This problem can be solved using various approaches:

Using Min Distance

If the order of elements in the list is not guaranteed, the min() function with the key parameter can be used. This method finds the minimum distance between each element and the target, and returns the element with the minimum distance:

def takeClosest(myList, myNumber):
    return min(myList, key=lambda x: abs(x - myNumber))
Copy after login

Using Binary Search (Bisection Method)

If the list is known to be sorted, binary search can be applied to find the closest number more efficiently in O(log n) time:

def takeClosest(myList, myNumber):
    low = 0
    high = len(myList) - 1
    while low <= high:
        mid = (low + high) // 2
        if myList[mid] == myNumber:
            return myList[mid]
        elif myList[mid] < myNumber:
            low = mid + 1
        else:
            high = mid - 1
    return min([myList[low], myList[high]], key=lambda x: abs(x - myNumber))
Copy after login

The above is the detailed content of How do you find the closest number in a list to a given value?. 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