This tutorial is about finding the nearest value in a list and return the value that is closest to the given value in the list. For example, suppose that the original list is [9,8,6,2,10] and the given value is 3. Then 6 should be returned as an output as it is the closest to 3. To find the closest match, we will practice different techniques and methods.
This tutorial discusses the following cases.
Given an input list and a value: List=[29, 32, 14, 19, 56, 97, 24, 46, 74] Input Value specified by user: 22 Problem 1: Find the closest value in the list. Output:24 Problem 2: When the two numbers are at equal distance List=[29, 32, 14, 19, 56, 97, 24, 46, 74] Input Value specified by user: 19 (a)find the closest lower value in the list. Output:14 (b)find the closest higher value in the list. Output:24 Problem 3:Find the two closest values in the given input list. List=[29, 14, 19, 56, 97, 32, 24, 46, 74] Input Value specified by user: 29,32
Let’s discuss all these cases for sorted and unsorted lists along with examples. learn more about Python Lists.
Problem 1: FIND THE NEAREST VALUE IN A LIST TO A user-specified input value
We can find the nearest value in the list by using the min() function. Define a function that calculates the difference between a value in the list and the given value and returns the absolute value of the result. Then call the min() function which returns the closest value to the given value. Let’s understand this through an example.
import numpy as np def closest_value(input_list, input_value): arr = np.asarray(input_list) i = (np.abs(arr - input_value)).argmin() return arr[i] if __name__ == "__main__" : list1 = [22, 12, 51, 23, 48, 16, 34, 61] num=int(input("Enter the value: ")) val=closest_value(list1,num) print("The closest value to the "+ str(num)+" is",val)
In the above code, the “np.asarray(input_list)” first converts the list into an array. Then, this “arr – input_value” command calculates the difference of all list values with the given value. After that, we have taken the absolute of the list values which converts the difference values i.e. [-21 -31 8 -20 5 -27 -9 18] to [21 31 8 20 5 27 9 18]. After that, argmin() function selects the minimum value in the list and returns its index. In this case, the minimum value is 5. Thus ‘i’ becomes equal to 4 and arr is equal to 48 which is returned by the function as an output. If you are asked to return the index of the closest value then you can do this by replacing ‘return arr[i]’ with ‘return i’. That is how this function finds the nearest value to the value specified by the user or the index of the nearest value.
The same program can also be implemented using the lambda function which shortens the length of a code. For more information, you can read about lambda functions here.
def closest_value(input_list, input_value): difference = lambda input_list : abs(input_list - input_value) res = min(input_list, key=difference) return res if __name__ == "__main__" : list1 = [22, 12, 51, 23, 48, 16, 34, 61] num=int(input("Enter the value: ")) val=closest_value(list1,num) print("The closest value to the "+ str(num)+" is",val)
Problem 2: find closest value When the two numbers are at equal distance
When the two numbers are at equal distance, the above programs mentioned in problem 1 will return the closest lower number in the list. When you are asked to return the closest higher number in the list, then the above code will not work. If we modify the code of example 2 by arranging the list elements in descending order then the greater value closest to the given value comes first. The program in example 3 shows the modified code.
def closest_value(input_list, input_value): input_list.sort(reverse=True) difference = lambda input_list : abs(input_list - input_value) res = min(input_list, key=difference) return res if __name__ == "__main__" : list1 = [29, 32, 14, 56, 97, 24, 46, 74] num=int(input("Enter the value: ")) val=closest_value(list1,num) print("The closest value to the "+ str(num)+" is",val)
problem 3: Find the two closest values in the list
Let’s move to the third problem now. Here we’ll discuss how to find the two closest values in a list in python. For this, we need to calculate the difference of each number with respect to every number. The numbers whose difference is found to be minimum will be the two closest values in the list. Let’s demonstrate this with code.
In the code given below, we have created a temp variable that will store the minimum difference. We have initialized it with the maximum value in the list. Then we have used two loops to traverse through the list. At the first iteration of for loop, the num1 variable stores the 2nd number i.e. 32 whereas the while loop will calculate the difference between all the values before 32 and store the minimum difference in the temp variable. The variables first_num and sec_num are the two numbers that generated the minimum result. Similarly, on the second iteration, the num1 becomes 14. The while loop first calculates the difference between 14 and 32, then decrements j and extracts the first element and num2 in the list.
list1 = [29, 32, 14, 56, 97, 24, 46, 74] temp=max(list1) for i in range(1, len(list1)): num1=list1[i] j=i-1 while(j>=0): num2=list1[j] res=abs(num1-num2) if res<temp: temp=res first_num=num1 sec_num=num2 j=j-1 print(first_num,sec_num)
This is the naive implementation that takes O(n^2) times. By efficiently implementing, you can reduce the time complexity to O(nlogn). Try to do modify this code for the case when there are multiple values that are close to each other. Let us know your feedback in the comments. See more Python Tutorials Here