"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How do you find the closest number in a list to a given value?

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

Published on 2024-11-19
Browse:229

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))

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 
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3