What is wrong with the following code for computing distance between all pairs of vectors?
<p>I'm trying to find manhattan distance between all pairs of vectors.</p>

<pre><code>import numpy as np
import itertools

class vector:
    def __init__(self):
        self.a = 0
        self.b = 0

c = vector()
d = vector()
l = vector()
m = vector()

e = [c,d]
n = [l,m]
o = np.array(n)
f = np.array(e)
p = itertools.product(o,f)
p = list(p)
def comp(x):
    return (x[0].a-x[1].a) + (x[0].b-x[1].b)

g = np.vectorize(comp)
print g(p)
</code></pre>

<p>I get the error:</p>

<pre><code>Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
  File "/usr/local/lib/python2.7/site-packages/numpy/lib/function_base.py", line 2207, in __call__
    return self._vectorize_call(func=func, args=vargs)
  File "/usr/local/lib/python2.7/site-packages/numpy/lib/function_base.py", line 2270, in _vectorize_call
    ufunc, otypes = self._get_ufunc_and_otypes(func=func, args=args)
  File "/usr/local/lib/python2.7/site-packages/numpy/lib/function_base.py", line 2232, in _get_ufunc_and_otypes
    outputs = func(*inputs)
  File "&lt;stdin&gt;", line 2, in comp
AttributeError: vector instance has no attribute '__getitem__'
</code></pre>

<p>The way you've written <code>comp</code>, it expects to be called with a two-tuple as an argument, but that's not what happens.  <code>p</code> is a list of tuples.  When you call a vectorized function on it, it is converted to a numpy array.  The tuples are split into separate columns so you get a 4x2 array.  Your function is then called on each cell of this array.  So it gets called with just one vector object as an argument.</p>

<p>It's not really clear what you're trying to accomplish here.  If your objects are not numbers, you won't gain anything by using things like <code>np.vectorize</code> on them; you should just call your function in a loop.  If your objects are numbers, then just store them in an ordinary numpy array, and make use of better ways to compute such distances, like the <code>pdist</code> function in <code>scipy</code>.</p>

python vectorization itertools