Wednesday 15 August 2012

python - sum of squares in a list in one line? -



python - sum of squares in a list in one line? -

to demonstrate have done sth. code sum in 3 lines.

l=[1,2,3,4,5]; sum=0 in l: sum+=i*i; print sum

i curious can in 1 line?

what :

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

we utilize reduce:

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

we can take first element, square number, add together head of list can create sure it's squared, go on using reduce. doesn't worth work have improve alternatives.

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

just curiosity, tried compare between 3 solutions sum square numbers of 10000 numbers generated range, , compute execution time of every operation.

l=range(10000) datetime import datetime start_time = datetime.now() print reduce(lambda x,y: x+y*y,l) print('using cut down numbers: {}'.format(datetime.now() - start_time)) 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)) datetime import datetime start_time = datetime.now() print sum( i*i in l) print('using list comprehension sum: {}'.format(datetime.now() - start_time))

output:

using list comprehension faster

333283335000 using cut down numbers: 0:00:00.003371 333283335000 sum after map square operation: 0:00:00.002044 333283335000 using list comprehension sum: 0:00:00.000916

python list sum

No comments:

Post a Comment