Skip to content Skip to sidebar Skip to footer

Multiply Adjacent Elements

I have a tuple of integers such as (1, 2, 3, 4, 5) and I want to produce the tuple (1*2, 2*3, 3*4, 4*5) by multiplying adjacent elements. Is it possible to do this with a one-liner

Solution 1:

Short and sweet. Remember that zip only runs as long as the shortest input.

printtuple(x*y for x,y inzip(t,t[1:]))

Solution 2:

>>>t = (1, 2, 3, 4, 5)>>>printtuple(t[i]*t[i+1] for i inrange(len(t)-1))
(2, 6, 12, 20)

Not the most pythonic of solutions though.

Solution 3:

tu = (1, 2, 3, 4, 5)

it = iter(tu).next
it()
printtuple(a*it() for a in tu)

I timed various code:

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): # indexingtuple(tu[x]*tu[x+1] for x inrange(len(tu)-1))
    A.append(clock()-te)

    te = clock()
    for ren in xrange(rentime): # ziptuple(x*y for x,y inzip(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): # iziptuple(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.135054036197zip0.134594201218iter0.100380634969
izip      0.0923947037962

izip is better than zip : - 31 %

My solution isn't so bad (I didn't think so by the way): -25 % relatively to zip, 10 % more time than champion izip

I'm surprised that indexing isn't faster than zip : nneonneo is right, zip is acceptable

Solution 4:

I like the recipes from itertools:

from itertools import izip, tee

defpairwise(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]

Post a Comment for "Multiply Adjacent Elements"