Dot product?

Craig Schardt lazrnerd at ufl.edu
Mon Dec 13 17:07:59 EST 1999


On Mon, 13 Dec 1999 09:52:36 +0000, Charles Boncelet
<boncelet at udel.edu> wrote:

>How about the the mxTools solution:
>
>sum = 0.0
>for x,y in tuples(list1, list2):
>    sum = sum + x*y
>

This could also be acheived with the following Python class:

class Iter:
    onelist = 0
    def __init__(self, *args):
        if len(args) == 1:
            self.onelist = 1
            self.items = args[0]
        else:
            self.items = args

    def __getitem__(self, index):
        if self.onelist:
            return self.items[index]
        values = []
        for seq in self.items:
            try:
                values.append(seq[index])
            except IndexError:
                values.append(None)
        for val in values:
            if val is not None:
                break
        else:
            raise IndexError
        return tuple(values)

Sorry for the lack of documentation but I just whipped it up. Just
call it as:

for i,j in Iter(list1,list2):
	dosomething(i,j)

>
>AFAIK, both "tuples" and "map" solutions create an intermediate object.
>However there seems to be no reason why the internals of Python couldn't 
>be changed so that these could be computed "on the fly" as needed.
>

The class version doesn't create any intermediate copies of the lists.
If this lists are large, this could be an advantage. Otherwise I can't
see any good justification for the extra overhead.

-craig.



More information about the Python-list mailing list