Friday, December 27, 2024
Google search engine
HomeLanguagesPython | Find closest number to k in given list

Python | Find closest number to k in given list

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


Output:

9.35

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


Output:

9.35

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


Output

9.35

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


Output

9.35

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)


Output

9.35

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.

RELATED ARTICLES

Most Popular

Recent Comments