Sunday, February 25, 2018

Python program : Sum of all the perfect squares in a List

Write a function sumsquares(l) that takes as input a list of integers and retuns the sum of all the perfect squares in l.

Here are some examples to show how your function should work.


>>> sumsquares([1,4,9])
14
>>> sumsquares([10,11,12,15])
0
>>> sumsquares([16,20,25,30,625])
666 
 
from math import * 
def sumsquares(l):
  sum=0
  
  for i in l:
    sqr=sqrt(float(i))
    if ((sqr-int(sqr))==0.0) :
      sum=sum + i
  return(int(sum))
 

No comments:

Post a Comment

What are 'Piecewise Functions'?

 A single function that uses different equations depending on the input , like f(x) = x for x < 0 and f(x) = x^2 for x >0. Such func...