Given a list of numbers and a variable K, where K is also a number, write a Python program to find the number in a list which is closest to the given number K.
Input : lst = [3.64, 5.2, 9.42, 9.35, 8.5, 8], K = 9.1 Output : 9.35 Input : lst = [9, 11, 5, 3, 25, 18], K = 6 Output : 5
Method #1 : Using
In this approach, we use
min method from Python and apply a key that finds the absolute difference of each element with K, and returns the element having minimum difference.
Method #2 : Using
This approach applies the same method but using numpy module. First we convert the given list to an array. Find absolute difference with K of each element, and return the minimum from it.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course