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 :
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)