简体   繁体   中英

sum of squares in a list in one line?

To demonstrate I have done sth. This is my code do sum in three lines.

l=[1,2,3,4,5];
sumOfList=0

for i in l:
    sumOfList+=i*i;
print sumOfList

I am curious can I do it in just one line?

Yes, you can. Here it is using the sum function:

l = [1,2,3,4,5]
print(sum(i*i for i in l))

What about :

sum(map(lambda x:x*x,l))

we also use reduce :

print reduce(lambda x,y: x+y*y,l) # as pointed by @espang reduce(lambda x,y: x+y*y,l) is only ok, when the first value is 1 (because 1*1 == 1). The first value is not squared

We can take the first element, get its square, then add it to the head of the list so we can make sure that it's squared. Then we continue using reduce. It isn't worth all that work, as we have better alternatives.

reduce(lambda x,y: x+y*y,[l[:1][0]**2]+l[1:])

Just out of curiosity, I tried to compare the three solutions to sum the squares of 10000 numbers generated by range , and compute the execution time of every operation.

l=range(10000) 
from datetime import datetime
start_time = datetime.now()
print reduce(lambda x,y: x+y*y,l)
print('using Reduce numbers: {}'.format(datetime.now() - start_time))

from datetime import datetime
start_time = datetime.now()
print sum(map(lambda x:x*x,l))
print('Sum after map square operation: {}'.format(datetime.now() - start_time))

from datetime import datetime
start_time = datetime.now()
print sum( i*i for i in l)
print('using list comprehension to sum: {}'.format(datetime.now() - start_time))

Output:

Using list comprehension is faster

333283335000
using Reduce numbers: 0:00:00.003371
333283335000
Sum after map square operation: 0:00:00.002044
333283335000
using list comprehension to sum: 0:00:00.000916

For bigger list and when performance matters you should use numpy:

import numpy as np
l = [1,2,3,4,5]
arr = np.array(l)

np.sum(arr**2)
# or better:
np.dot(arr, arr)

You could define a function and use list comprehension

l = [2, 6, 10, 12, 16, 20]

def sumOfSquares(alist):
return ((sum([i**2 for i in alist]))-(sum(alist)**2)/len(alist))

print(sumOfSquares(l))
l = [1, 2, 3, 4, 5, 6]

sum(np.multiply(l,l))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM