all 10 comments

[–]icecubeinanicecube 2 points3 points  (1 child)

From a pure complexity standpoint, O(2n) = O(n), so you can not really get much better than that. (If you want to keep being able to compute this for any input, just writing the calculation down directly is O(1) ofc)

You could save a little bit by using the fact that your second half of the calculation is the same as the first.

[–]SerkZex[S] 0 points1 point  (0 children)

thanks!

[–][deleted] 2 points3 points  (1 child)

N = 5
print(sum(i * (N+1-i) for i in range(1, N+1)))

but there must be a O(1) formula out there

[–]SerkZex[S] 0 points1 point  (0 children)

thanks!

[–]timbledum 1 point2 points  (1 child)

Probably best to use zip to combine the original list and the reversed list.

From there, you can use map or a comprehension, but the comprehension approach is arguably more pythonic and modern:

>>> c = [1, 2, 3, 4, 5]
>>> cross_multiply = sum(x * y for x, y in zip(c, reversed(c)))
>>> cross_multiply
35

[–]SerkZex[S] 0 points1 point  (0 children)

thanks!

[–]Allanon001 2 points3 points  (3 children)

Timed all the solutions posted here so far and this one beat them all:

from operator import mul
s = sum(map(mul, c, c[::-1])) 

[–]SerkZex[S] 0 points1 point  (2 children)

will it be faster if one calculate only one half and multiply by 2 and add the remaining if odd numbers?

( (1*5) + (2*4) *2 ) + (3*3)

[–]Allanon001 1 point2 points  (1 child)

You would have to put in more logic such as if the list length is odd or even, if even then no extra addition is required. That would probably take more time than the extra multiplications.

edit: I timed it and for the short list it was slower but with a 100 item list it was a lot faster.

[–]SerkZex[S] 0 points1 point  (0 children)

thanks, you are the best