Python Perfect Square

前端 未结 3 759
无人共我
无人共我 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条回答
  • 2021-01-27 07:57

    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)
    
    0 讨论(0)
  • 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)]
    
    0 讨论(0)
  • 2021-01-27 08:16
    x=int(input())
    if x>0:
        for i in range(x):
            p=i**2
            print(p)
    
    0 讨论(0)
提交回复
热议问题