'Python | Give list [1,2,3,4] -> return 1*2+2*3+3*4
So as i said in the title, i want to multipy each two neigbors in the list and sum them all - with a single code line.
I'm looking for the most elegant and efficient method, without using extra memory or such.
Here's what I do have now:
import numpy as np
G = lambda array: sum(np.multiply(array[:-1], array[1:])))
That works, but when i write array[:-1] and array[1:], doesn't it create two new arrays? If so, is there a way to do that with the same original array?
Or maybe you can come up with a nicer way to do that :)
Solution 1:[1]
Try the following:
lst = [1,2,3,4]
func = lambda lst: sum([lst[i]*lst[i+1] for i in range(len(lst)-1)])
func(lst)
Solution 2:[2]
The actual numpy way
array = np.array([1, 2, 3, 4])
array[1:] @ array[:-1]
Out[]: 20
@ is the dot-product operator, which is what that multiply-sum operation is called normally.
If you're wedded to the lambda, it would be:
G = lambda array: array[1:] @ array[:-1]
Solution 3:[3]
If you're not constrained by the lambda you can:
def sum_with_neighbours(arr: list[int]) -> int:
sum_ = 0
for i in range(len(arr) - 1): # -1 because we want to go until second-last item
sum_ += arr[i] * arr[i + 1]
return sum_
Solution 4:[4]
itertools.pairwise may be the most pythonic choice:
>>> from itertools import pairwise
>>> [*pairwise(range(5))]
[(0, 1), (1, 2), (2, 3), (3, 4)]
>>> sum(i * j for i, j in pairwise(range(5)))
20
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Keziya |
| Solution 2 | Daniel F |
| Solution 3 | zkscpqm |
| Solution 4 |
