user2469891
user2469891

Reputation: 31

Multiply adjacent elements of list and add them

I want to successively multiply adjacent element of the list and add the multiplication:

Upvotes: 1

Views: 3257

Answers (6)

rr-
rr-

Reputation: 14831

Try this:

x=[1,2,3,4]
print sum(a*b for a,b in zip(x, x[1:]))
#prints 20

Upvotes: 3

John La Rooy
John La Rooy

Reputation: 304355

A generator expression without any list slices/copies

>>> mylist = [1,2,3,4]
>>> sum(mylist[i-1] * j for i, j in enumerate(mylist) if i)
20

Upvotes: 0

poke
poke

Reputation: 388003

Using the pairwise itertools recipe:

>>> sum(a * b for (a, b) in pairwise([1, 2, 3, 4]))
20
>>> sum(a * b for (a, b) in pairwise([1, 2, 3]))
8

What I need to change if want function([1,2,3,4]) perform (1*2*3*4)?

>>> from functools import reduce
>>> from operator import mul
>>> reduce(mul, [1, 2, 3, 4])
24

Upvotes: 3

inspectorG4dget
inspectorG4dget

Reputation: 114025

In [88]: mylist = [1,2,3,4]

In [89]: sum(itertools.imap(lambda t: operator.mul(*t), itertools.izip(mylist, itertools.islice(mylist, 1, len(mylist)))))
Out[89]: 20

Upvotes: 0

Inbar Rose
Inbar Rose

Reputation: 43467

Function using sum, map, lambda and zip

def my_math(lst):
    return sum(map(lambda x: x[0]*x[1], zip(lst,  lst[1:])))

>>> my_math([1,2,3])
8
>>> my_math([1,2,3,4])
20
>>> my_math([1,2,3,4,5])
40

Upvotes: 1

Rohit Jain
Rohit Jain

Reputation: 213321

Using list comprehension:

>>> mylist = [1,2,3,4]
>>> sum(mylist[i] * mylist[i + 1] for i in range(len(mylist) - 1))
20

Upvotes: 3

Related Questions