Python | Find closest number to k in given list
Last Updated :
17 May, 2023
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.
Examples:
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 min() method 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.
Python3
# Python3 program to find Closest number in a list
def closest(lst, K):
return lst[min(range(len(lst)), key = lambda i: abs(lst[i]-K))]
# Driver code
lst = [3.64, 5.2, 9.42, 9.35, 8.5, 8]
K = 9.1
print(closest(lst, K))
Method #2 : Using numpy module 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.
Python3
# Python3 program to find Closest number in a list
import numpy as np
def closest(lst, K):
lst = np.asarray(lst)
idx = (np.abs(lst - K)).argmin()
return lst[idx]
# Driver code
lst = [3.64, 5.2, 9.42, 9.35, 8.5, 8]
K = 9.1
print(closest(lst, K))
Method #3: Using the heapq.nsmallest() function
This method uses the heapq.nsmallest() function to find the smallest element in the list, based on the absolute difference between each element and K. The function takes three arguments: the number of items to return, the list to search through, and a key function that is used to determine the value to compare each element with.
Python3
import heapq
def closest(lst, K):
#using heapq.nsmallest() to find the element in the list with the smallest absolute difference with K
return heapq.nsmallest(1, lst, key=lambda x: abs(x-K))[0]
lst = [3.64, 5.2, 9.42, 9.35, 8.5, 8]
K = 9.1
print(closest(lst, K))
#This code is contributed by Edula Vinay Kumar Reddy
The time complexity of the Method #3 using heapq.nsmallest() function is O(n log k) where n is the length of the list and k is the number of items to return. The function is based on a priority queue, which takes O(log k) to extract the smallest element and O(n log k) to iterate through the list and insert each element into the priority queue.
The auxiliary space is O(1).
Approach#4: Using sort()+abs()
We can sort the list in ascending order and then iterate over it, keeping track of the closest number to k as we go. We can terminate the loop as soon as we find a number greater than k, because the list is sorted and any subsequent numbers will be even farther away.
Algorithm
1. Sort the list in ascending order.
2. Initialize a variable closest_num to the first element of the sorted list.
3. Iterate over the sorted list.
4. For each element, if it is closer to k than closest_num, update closest_num to be that element.
5. If an element greater than k is encountered, terminate the loop.
6. Return closest_num.
Python3
def find_closest(lst, k):
lst.sort()
closest_num = lst[0]
for num in lst:
if abs(num - k) < abs(closest_num - k):
closest_num = num
if num > k:
break
return closest_num
lst = [3.64, 5.2, 9.42, 9.35, 8.5, 8]
k = 9.1
print(find_closest(lst, k))
Time Complexity: O(n log n) due to the sorting operation.
Auxiliary Space: O(1) because we are not using any additional data structures.
Approach#5: Using bisect module
First, the given list is sorted in ascending order. Then, the bisect_left() function is used to find the index of the element in the list that is equal to or greater than k. If the index is 0, it means that k is smaller than all the elements in the list, so the first element is chosen as the closest element. If the index is equal to the length of the list, it means that k is greater than all the elements in the list, so the last element is chosen as the closest element.Otherwise, the element before and after the index are considered and the one with the smaller absolute difference from k is chosen as the closest element.
Algorithm
The code finds the element in a sorted list lst that is closest to a given value k. It uses the bisect module to find the index of the leftmost element greater than or equal to k. Then it checks the neighboring elements to determine which one is closer to k. The closest element is returned.
Python3
import bisect
lst = [3.64, 5.2, 9.42, 9.35, 8.5, 8]
k = 9.1
lst.sort()
index = bisect.bisect_left(lst, k)
if index == 0:
closest = lst[0]
elif index == len(lst):
closest = lst[-1]
else:
before = lst[index-1]
after = lst[index]
closest = before if after-k > k-before else after
print(closest)
Time complexity: O(log n) due to the use of binary search in bisect module.
Auxiliary Space: O(1) since only a few variables are used and the size of the input list does not affect the memory used.
Similar Reads
Python Program to Find closest number in array Given an array of sorted integers. We need to find the closest value to the given number. Array may contain duplicate values and negative numbers. Examples: Input : arr[] = {1, 2, 4, 5, 6, 6, 8, 9} Target number = 11 Output : 9 9 is closest to 11 in given array Input :arr[] = {2, 5, 6, 7, 8, 8, 9};
4 min read
Python - Closest Sum Pair in List Sometimes, we desire to get the elements that sum to a particular element. But in cases we are not able to find that, our aim changes to be one to find the closest one. This can have application in many domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using diction
4 min read
Python program to find smallest number in a list In this article, we will discuss various methods to find smallest number in a list. The simplest way to find the smallest number in a list is by using Python's built-in min() function.Using min()The min() function takes an iterable (like a list, typle etc.) and returns the smallest value.Pythona = [
2 min read
Python program to find smallest number in a list In this article, we will discuss various methods to find smallest number in a list. The simplest way to find the smallest number in a list is by using Python's built-in min() function.Using min()The min() function takes an iterable (like a list, typle etc.) and returns the smallest value.Pythona = [
2 min read
Python program to find smallest number in a list In this article, we will discuss various methods to find smallest number in a list. The simplest way to find the smallest number in a list is by using Python's built-in min() function.Using min()The min() function takes an iterable (like a list, typle etc.) and returns the smallest value.Pythona = [
2 min read
Python | Find the closest Key in dictionary The search of keys in dictionary in python has been discussed many times. But sometimes, we may have a problem in which we require to fetch the key which is the nearest one of the given keys. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + keys(
2 min read