Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading