title: Python: How to find two equal/closest values between two separate arrays?
body: <p>Let's say we have two arrays of equal length:</p>
  
  <pre><code>arr1 = (21, 2, 3, 5, 13)
  arr2 = (10, 4.5, 9, 12, 20)
  </code></pre>
  
  <p>Which variable from <code>arr1</code> is <strong>equal / closest</strong> to a variable from <code>arr2</code>?</p>
  
  <p>Looking at these two lists we can easily say that the closest numbers are <strong>4.5</strong> and <strong>5</strong>. I've tried to implement a function that returns two closest values given two lists and it kinda <em>works</em> 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:</p>
  
  <pre><code>arr1 = (21, 2, 3, 5, 13)
  arr2 = (10, 4.5, 9, 12, 18)
  </code></pre>
  
  <p>the values the function returns are 13 and 18</p>
  
  <p>Here is the function:</p>
  
  <pre><code>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 &lt;= 1 and r &gt;= lr[0][2]:
                  lr.pop()
                  lr.append([x1, x2, r])
      return lr
  </code></pre>
  
  <p>Can you come up with a better one?</p>