Dot product?
David C. Ullrich
ullrich at math.okstate.edu
Sun Dec 12 14:52:10 EST 1999
Excellent - thanks. Never noticed map took more than two parameters.
Mike Fletcher wrote:
> 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...
I haven't been paying close enough attention to know what you mean
by that - it's going to be replaced in the next version, or it's going to be
replaced by the interpreter on compile?
So I dunno what's so rebellious about your post. I do want a Transpose
fairly regularly, and it seems to me that getting my Transose from one
call to one built-in function must be at least as efficient as the code I'm
not willing to show you that did it by hand.(???)
> 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 )
Don't seem so silly to me - for the second between the time when I
saw the Transpose(a,b) and the time I saw this I was planning on
figuring out how to make it work for any number of sequences.
(Pretty sure I could got that one, having seen how to do it for two...)
> ...
> >>> Transpose( a, b )
> [(2, 3), (3, 4), (4, 5)]
> >>> Transpose( a, b, () )
> [(2, 3, None), (3, 4, None), (4, 5, None)]
> >>>
>
> Enjoy,
I'm having fun with it already.
>
> Mike
DU
More information about the Python-list
mailing list