Reputation: 31
I want to successively multiply adjacent element of the list and add the multiplication:
([1,2,3,4])
should perform (1*2+2*3+3*4)
, and [1,2,3]
I want to get 8
because (1*2)+(2*3)
Upvotes: 1
Views: 3257
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
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
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
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
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
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