Python Program at Perfect Squares

I wrote this python function that takes a list as a parameter and determines which list items are perfect squares and then returns a new list of only those select items.

Here is my function:

def square(n):
    return n**2

def perfectSquares1(L):
    import math
    m=max(L)
    for n in L:
        if type(n) is int and n>0:
            Result=map(square,range(1,math.floor(math.sqrt(m))))
            L1=list(Result)
    L2=list(set(L).intersection(set(L1)))
    return L2

      

But now I'm trying to rework it a bit: I want to write a one-line boolean function that takes n as a parameter and returns True if n is a perfect square and returns false otherwise.

Any advice? I can't seem to find a way to do this in just one line.

+2


source to share


3 answers


You can do:

import math
def perfect_sq(n):
    return n == int(math.sqrt(n)) * int(math.sqrt(n))

      



Or you can use:

import math
def perfect_sq(n):
    return n == int(math.sqrt(n)) ** 2

      

+3


source


lambda n: math.sqrt(n) % 1 == 0

      



+5


source


The modulo operator can be used:

>>> def perfectsquare(n):
...     return not n % n**0.5
...
>>> perfectsquare(36)
True
>>> perfectsquare(37)
False
>>> perfectsquare(25)
True
>>> perfectsquare(4215378*4215378)
True

      

+1


source







All Articles