comparison - Python: How to find two equal/closest values between two separate arrays? -
let's have 2 arrays of equal length:
arr1 = (21, 2, 3, 5, 13) arr2 = (10, 4.5, 9, 12, 20)
which variable arr1
equal / closest variable arr2
?
looking @ these 2 lists can closest numbers 4.5 , 5. i've tried implement function returns 2 closest values given 2 lists , kinda works examples above, barely solution because not optimal. , can check function fails when change arrays this:
arr1 = (21, 2, 3, 5, 13) arr2 = (10, 4.5, 9, 12, 18)
the values function returns 13 , 18
here function:
def get_nearest(arr1, arr2): lr = [[0, 0, 0]] x1 in arr1: x2 in arr2: r = (x1 / x2 % (x1 + x2)) print x1, x2, r if r <= 1 , r >= lr[0][2]: lr.pop() lr.append([x1, x2, r]) return lr
can come better one?
is speed issue? care ties? if not, 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) (a1, a2) in product(arr1, arr2)]
yields list of n**2
pairs of numbers:
[(21, 10), (21, 4.5), ..., (13, 12), (13, 20)]
then sort them absolute difference (|a1 - a2|
) using sorted
. passing sorted
key
keyword, tell sorted
use sorting criteria lambda t: abs(t[0] - t[1])
. pair smallest absolute difference placed in first index of sorted array, can grab tacking [0]
on end.
edit:
as suggested piotr in comments, can feed key=func
min
, max
, speeds considerably. try instead:
from itertools import product min(product(arr1, arr2), key=lambda t: abs(t[0]-t[1]))[0]
Comments
Post a Comment