Multiply Adjacent Elements
5 answers
If t is your tuple:
>>> tuple(t[x]*t[x+1] for x in range(len(t)-1))
(2, 6, 12, 20)
And another solution with a lovely map:
>>> tuple(map(lambda x,y:x*y, t[1:], t[:-1]))
(2, 6, 12, 20)
Edit: And if you're worried about extra chunk memory, you can use islice from itertools, which will iterate over your tuple (thanks @eyquem):
>>> tuple(map(lambda x,y:x*y, islice(t, 1, None), islice(t, 0, len(t)-1)))
(2, 6, 12, 20)
+3
user2070336
source
to share
tu = (1, 2, 3, 4, 5) it = iter(tu).next it() print tuple(a*it() for a in tu)
I have timed various codes:
from random import choice
from time import clock
from itertools import izip
tu = tuple(choice(range(0,87)) for i in xrange(2000))
A,B,C,D = [],[],[],[]
for n in xrange(50):
rentime = 100
te = clock()
for ren in xrange(rentime): # indexing
tuple(tu[x]*tu[x+1] for x in range(len(tu)-1))
A.append(clock()-te)
te = clock()
for ren in xrange(rentime): # zip
tuple(x*y for x,y in zip(tu,tu[1:]))
B.append(clock()-te)
te = clock()
for ren in xrange(rentime): #i ter
it = iter(tu).next
it()
tuple(a*it() for a in tu)
C.append(clock()-te)
te = clock()
for ren in xrange(rentime): # izip
tuple(x*y for x,y in izip(tu,tu[1:]))
D.append(clock()-te)
print 'indexing ',min(A)
print 'zip ',min(B)
print 'iter ',min(C)
print 'izip ',min(D)
result
indexing 0.135054036197
zip 0.134594201218
iter 0.100380634969
izip 0.0923947037962
izip is better than zip: - 31%
My solution is not that bad (I don't think so by the way): -25% relative to zip, 10% longer than izip champion
I'm surprised indexing is not faster than zip: nneonneo is right, zip is acceptable
+3
source to share
I like recipes fromitertools
:
from itertools import izip, tee
def pairwise(iterable):
xs, ys = tee(iterable)
next(ys)
return izip(xs, ys)
print [a * b for a, b in pairwise(range(10))]
Result:
[0, 2, 6, 12, 20, 30, 42, 56, 72]
+2
source to share