Dot product?

David C. Ullrich ullrich at math.okstate.edu
Sat Dec 11 15:50:37 EST 1999


    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




More information about the Python-list mailing list