Finding the two closest numbers in a list using sorting
Such a method will do what you want:
>>> def minDistance(lst):
lst = sorted(lst)
index = -1
distance = max(lst) - min(lst)
for i in range(len(lst)-1):
if lst[i+1] - lst[i] < distance:
distance = lst[i+1] - lst[i]
index = i
for i in range(len(lst)-1):
if lst[i+1] - lst[i] == distance:
print lst[i],lst[i+1]
In the first for
loop we find out the minimum distance, and in the second loop, we print all the pairs with this distance. Works as below:
>>> lst = (1,2,3,6,12,9,1.4,145,12,83,53,12,3.4,2,7.5)
>>> minDistance(lst)
2 2
12 12
12 12
>>>
What is the least expensive way to find the two closest numbers surrounding a given value in a list of numbers?
Try the code below:
List<int> numbers = new List<int>(){ 6, 7, 8, 9, 1, 2, 3, 4, 5 };
int middle = 6;
var min = numbers.Where(y => y < middle).Max(); // min = 5
var max = numbers.Where(y => y > middle).Min(); // max = 7
The code above will work fine for sorted and unsorted lists.
If you can't be certain that you have at least one min and/or one max value, you must do this, otherwise you'll get an Exception:
var min = numbers.Where(y => y < middle).DefaultIfEmpty().Max();
var max = numbers.Where(y => y > middle).DefaultIfEmpty().Min();
And, in the case you are sure 100% of the time that the list is sorted, you can save a bit of performance doing the code below:
var min = numbers.LastOrDefault(y => y < middle);
var max = numbers.FirstOrDefault(y => y > middle);
I hope it helped you.
Python: How to find two equal/closest values between two separate arrays?
Is speed an issue? Do you care about ties? If not, what about something simple like
from itertools import product
sorted(product(arr1, arr2), key=lambda t: abs(t[0]-t[1]))[0]
For both
arr1 = (21, 2, 3, 5, 13)
arr2 = (10, 4.5, 9, 12, 20)
and
arr1 = (21, 2, 3, 5, 13)
arr2 = (10, 4.5, 9, 12, 18)
this yields
(5, 4.5)
Explanation:
product(arr1, arr2) = [(a1, a2) for (a1, a2) in product(arr1, arr2)]
yields a list of all N**2
pairs of numbers:
[(21, 10), (21, 4.5), ..., (13, 12), (13, 20)]
Then we sort them by the absolute difference (|a1 - a2|
) using sorted
. By passing sorted
the key
keyword, we tell sorted
to use the sorting criteria lambda t: abs(t[0] - t[1])
. The pair with the smallest absolute difference is placed in the first index of the sorted array, so we can grab it by tacking [0]
on the end.
Edit:
As suggested by Piotr in the comments, you can feed a key=func
to min
and max
, which speeds this up considerably. Try instead:
from itertools import product
min(product(arr1, arr2), key=lambda t: abs(t[0]-t[1]))[0]
Retrieving 2 closest numbers among 3
Call the three numbers A, B, and C.
Compute three variables:
AB = (A - B)^2
BC = (B - C)^2
CA = (C - A)^2
Then compare AB, BC, and CA. If AB is smallest, output A and B. If BC is smallest, output B and C. If CA is smallest, output C and A.
If you want to make it a bit more elegant, create a structure that consists of three numbers and create three such structures as follows:
S1 = (A-B)^2, A, B
S2 = (B-C)^2, B, C
S3 = (C-A)^2, C, A
Then sort S1,S2,S3 based on the first number. For the entry that sorts first, output its second two numbers.
Given two lists of ints, how can we find the closes number in one list from the other one?
>>> a = [1, 4, 11, 20, 25]
>>> b = [3, 10, 20]
>>>
>>> ans = list(map(lambda y:min(a, key=lambda x:abs(x-y)),b))
>>> ans
[4, 11, 20]
It's a loop for the question 'get number closest given a value'
value = #number
min(a, key=lambda x:abs(x-value))
Find the closest elements above and below a given number
Sorting is not necessary, and makes this time complexity O(n logn) when it should be just O(n).
I believe this is what you're looking for, taking advantage of numpy array indexing:
>>> # the smallest element of myArr greater than myNumber
>>> myArr[myArr > myNumber].min()
44
>>> # the largest element of myArr less than myNumber
>>> myArr[myArr < myNumber].max()
4
Related Topics
A Better Way Than Looping and Calling Functions That Loop and Call Another Functions
Psycopg2 Insert Python Dictionary as Json
Get All Rows That Have Same Value in Pandas
Printing Simple Diamond Pattern in Python
Calculate Final Letter Grade in Python Given 4 Test Scores
Pyqt: Getting Widgets to Resize Automatically in a Qdialog
How to Extract Table Names and Column Names from SQL Query
Exclude First Row When Importing Data from Excel into Python
How to Convert SQL Query Results into a Python Dictionary
Error Opening File in H5Py (File Signature Not Found)
Splitting Dataframe into Multiple Dataframes
Python - How to Check If Table Exists
How to Make a Grade Calculator in Python
How to Read Image Data from a Url in Python
Typeerror: Strptime() Argument 1 Must Be Str, Not List
How to Extract Data from Dictionary in the List