Python Perfect Square

前端 未结 3 763
无人共我
无人共我 2021-01-27 07:40

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(         


        
3条回答
  •  猫巷女王i
    2021-01-27 08:03

    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)]
    

提交回复
热议问题