Python: How to find two equal/closest values between two separate arrays?
comparison, python
Solution
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]
Problem
Let's say we have two arrays of equal length: ``` arr1 = (21, 2, 3, 5, 13) arr2 = (10, 4.5, 9, 12, 20) ``` Which variable from `arr1` is equal / closest to a variable from `arr2`? Looking at these two lists we can easily say that the closest numbers are 4.5 and 5. I've tried to implement a function that returns two closest values given two lists and it kinda works for the examples above, but it is barely a solution because it is not optimal. And you can easily check that the function fails when we slightly change the arrays like this: ``` arr1 = (21, 2, 3, 5, 13) arr2 = (10, 4.5, 9, 12, 18) ``` the values the function returns are 13 and 18 Here is the function: ``` def get_nearest(arr1, arr2): lr = [[0, 0, 0]] for x1 in arr1: for x2 in arr2: r = (x1 / x2 % (x1 + x2)) print x1, x2, r if r <= 1 and r >= lr[0][2]: lr.pop() lr.append([x1, x2, r]) return lr ``` Can you come up with a better one?