2

I wrote this python function which takes a list as a parameter and determines which elements of the list are perfect squares and then returns a new list of just those select elements.

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 re-work it a little: 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 figure out a way to make it only one line.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
user2553807
  • 329
  • 5
  • 10
  • 22

3 Answers3

6
lambda n: math.sqrt(n) % 1 == 0
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
3

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
TerryA
  • 58,805
  • 11
  • 114
  • 143
karthikr
  • 97,368
  • 26
  • 197
  • 188
  • Wasn't my downvote, but `perfect_sq(11)` returns True for me. – DSM Jul 07 '13 at 03:04
  • How can I get the function to return 'true' though? – user2553807 Jul 07 '13 at 03:10
  • Every number is a perfect square, 11 is a perfect square of 11**0.5. This questions is only interesting if we talk about integers. – Akavall Jul 07 '13 at 03:21
  • Yea, I just went full stupid. Sorry about that xD – TerryA Jul 07 '13 at 03:23
  • Note that this will fail for sufficiently large numbers because `math.sqrt` only has double precision, but to get around that you'd need to use an arbitrary-precision float calculation (like in `Decimal`) or implement an integer root algorithm (of which several are given in the question Haidro linked.) – DSM Jul 07 '13 at 03:25
1

Could use the modulo operator:

>>> def perfectsquare(n):
...     return not n % n**0.5
...
>>> perfectsquare(36)
True
>>> perfectsquare(37)
False
>>> perfectsquare(25)
True
>>> perfectsquare(4215378*4215378)
True
TerryA
  • 58,805
  • 11
  • 114
  • 143