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?