Dot product?
Mike Fletcher
mfletch at tpresence.com
Sat Dec 11 16:20:29 EST 1999
Maybe not what you were asking, but some food for thought :) . Of course,
we're told that all this mapping and reducing will get replaced by list
comprehensions, so maybe I shouldn't post this... oh well, I'll be a rebel
;) .
>>> import operator
>>> a = (2,3,4)
>>> b = (3,4,5)
>>> def Transpose( a, b ):
... return map( None, a, b )
...
>>> Transpose( a, b )
[(2, 3), (3, 4), (4, 5)]
>>> def Dot( a, b ):
... return reduce( operator.add, map( operator.mul, a, b))
...
>>> Dot( a, b )
38
>>> def Transpose( *args ):
... '''General version, takes any number of sequences (kind of silly
anyway :) )'''
... return apply( map, (None,)+args )
...
>>> Transpose( a, b )
[(2, 3), (3, 4), (4, 5)]
>>> Transpose( a, b, () )
[(2, 3, None), (3, 4, None), (4, 5, None)]
>>>
Enjoy,
Mike
-----Original Message-----
From: David C. Ullrich [mailto:ullrich at math.okstate.edu]
Sent: Saturday, December 11, 1999 3:51 PM
To: python-list at python.org
Subject: Dot product?
Ok, so I'm dense. How do I take the traditional "dot product"
of two vectors? In a nice Pythonic sort of way, I mean. Say
the vectors are represented as sequences of numerics - then
of course I can say just
def Dot(X, Y):
res = 0
for j in range(len(X)):
res = res + X[j] * Y[j]
return res
and that gives the right answer, but it doesn't look right -
seems like the Python way would involve a "for x in X"
instead of that "for j in range(len(X))".
For example if Transpose returns the transpose of a
sequence of sequences (ie Transpose(s)[j][k] = s[k][j])
I can say
def Dot(X, Y):
res = 0
for (x,y) in Transpose((X,Y)):
res = res + x * y
return res
and that looks "right". For that matter once I have a
Transpose I could just use reduce. But when I write
a Transpose routine I have the same complaints with
the way it looks, only more so.
Is there a keen way to do this sort of thing, or do I
just have to use the index as above? (Come to think
of it I think what I really want is a nice Transpose -
that's been coming up a lot, Dot is just one place.)
DU
--
http://www.python.org/mailman/listinfo/python-list
More information about the Python-list
mailing list