I\'m writing a function that takes a list L as a parameter and returns a list consisting of all the elements in L that are perfect squares.
def isPerfectSquare(
This is a good place to use lambda
. Also, no need to use list()
if Python 2.x or the extra parens.
import math
def perfectSquares2(L):
return filter(lambda n: n==int(math.sqrt(n))**2, L)
You have to import math
in isPerfectSquare
, otherwise it is just imported in the local scope of the perfetSquares2
function.
However, PEP 8 suggests you put module imports at the top of scripts:
import math
def isPerfectSquare(n):
return n==int(math.sqrt(n))**2
def perfectSquares2(L):
return(list(filter(isPerfectSquare,(L))))
By the way, I think a list comprehension may be faster here:
def perfectSquares2(L):
return [i for i in L if isPerfectSquare(i)]
x=int(input())
if x>0:
for i in range(x):
p=i**2
print(p)