title: python: algorithm for swapping elements between two arrays
body: <p>I am analyzing counting <a href="https://codility.com/media/train/2-CountingElements.pdf" rel="nofollow">example</a> in python presented by Codility</p>
  
  <p>I don't understand the logic used in the last loop (5 last rows) of this algorithm. 
  <br> Can anybody help please?</p>
  
  <p>The problem:</p>
  
  <blockquote>
    <p>You are given an integer <code>m</code> (<code>1 &lt; m &lt; 1000000</code>) and two non-empty,
    zero-indexed arrays <code>A</code> and <code>B</code> of <code>n</code> integers, <code>a0</code>, <code>a1</code>, ... ,
    <code>an−1</code> and <code>b0</code>, <code>b1</code>, ... , <code>bn−1</code> respectively (<code>0 &lt; ai</code>, <code>bi &lt; m</code>).
    The goal is to check whether there is a swap operation which can be
    performed on these arrays in such a way that the sum of elements in
    array <code>A</code> equals the sum of elements in array <code>B</code> after the swap. By
    swap operation we mean picking one element from array <code>A</code> and one
    element from array <code>B</code> and exchanging them.</p>
  </blockquote>
  
  <p>The solution:</p>
  
  <pre><code>def counting(A, m):
     n = len(A)
     count = [0] * (m + 1)
     for k in xrange(n):
         count[A[k]] += 1
     return count
  
  
  def fast_solution(A, B, m):
      n = len(A)
      sum_a = sum(A)
      sum_b = sum(B)
      d = sum_b - sum_a
      if d % 2 == 1:
          return False
      d //= 2
      count = counting(A, m)
      for i in xrange(n):
          if 0 &lt;= B[i] - d and B[i] - d &lt;= m and count[B[i] - d] &gt; 0:
              return True
      return False
  </code></pre>