Dot product?
Berthold Höllmann
bhoel at server.python.net
Sat Dec 11 18:04:29 EST 1999
"David C. Ullrich" <ullrich at math.okstate.edu> writes:
> 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
>
How about:
def Dot(X, Y):
res = 0.
for (x,y) in map(None, 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.)
>
Cheers
Berthold
--
bhoel at starship.python.net / http://starship.python.net/crew/bhoel/
It is unlawful to use this email address for unsolicited ads
(USC Title 47 Sec.227). I will assess a US$500 charge for
reviewing and deleting each unsolicited ad.
More information about the Python-list
mailing list