title: Memoize a NumPy vectorized function
body: <p>I have a function <strong>is_prime(n)</strong> which returns <em>True</em> if <em>n</em> is prime and <em>False</em> otherwise. In NumPy I am looping, checking if an array contains primes, and the start of the array will be identical through every iteration, so I want to memoize the <strong>is_prime(n)</strong> function to avoid a lot of unnecessary calculations. </p>
  
  <p>Since I have an array, I want to vectorize <strong>is_prime(n)</strong> so I can apply it on arrays element by element, NumPy style. I do this with one line from the NumPy tutorial (shown later)</p>
  
  <p>I also use a memoization template I found on the net:</p>
  
  <pre><code>def memoize(function):
      cache = {}
      def decorated_function(*args):
          if args in cache:
              return cache[args]
          else:
              val = function(*args)
              cache[args] = val
              return val
      return decorated_function
  </code></pre>
  
  <p>Then:</p>
  
  <pre><code>is_prime = memoize(is_prime)
  </code></pre>
  
  <p><strong>BUT</strong>, is V_prime now correctly memoized if i <strong>now</strong> vectorize the memoized <strong>is_prime</strong> function?:</p>
  
  <pre><code>V_prime = np.vectorize(is_prime)
  </code></pre>
  
  <p>Thank you</p>