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 :)
CodePudding user response:
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)
CodePudding user response:
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_
CodePudding user response:
For normal lists, using sum
and zip
should be fairly efficient:
f = lambda lst: sum(x * y for x, y in zip(lst[1:], lst))
f([1, 2, 3, 4])
Output:
20
CodePudding user response:
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
CodePudding user response:
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.