1

I want to identify numbers which are perfect squares in a list of numbers, for example:

a = [3, 4, 8, 16, 21, 58, 144]  # return [4, 16, 144]
tristansokol
  • 4,054
  • 2
  • 17
  • 32
Narendra
  • 1,511
  • 1
  • 10
  • 20

4 Answers4

7

Once approach is to build a predicate (a function returning true or false) and apply it with filter():

>>> def is_perfect_square(n):
        return round(n ** 0.5) ** 2 == n

>>> list(filter(is_perfect_square, [3, 4, 8, 16, 21, 58, 144]))
[4, 16, 144]

Or for those who prefer list comprehensions over filter():

>>> [x for x in [3, 4, 8, 16, 21, 58, 144] if is_perfect_square(x)]
[4, 16, 144]

The perfect square test works by taking the square root of a number and rounding it to the nearest integer, re-squaring it and comparing it to a the original number. The square root step can suffer a little round-off error, but the re-squaring of the rounded integer will be exact. This should be somewhat robust except for very large inputs.

Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485
3

You can combine math.sqrt() and is_integer() to filter the list, like the following:

import math

a = [3, 4, 8, 16, 21, 58, 144]
print [x for x in a if math.sqrt(x).is_integer()]
Yedhu Krishnan
  • 1,225
  • 15
  • 31
0

You can try:

>>> square_list = []
>>> a = [3, 4, 8, 16, 21, 58, 144]
>>> def perfect_square(number):
    return (number**0.5) % int(number**0.5) == 0

>>> for data in a:
    if perfect_square(data):
        square_list.append(data)


>>> print square_list
[4, 16, 144]
Harsha Biyani
  • 7,049
  • 9
  • 37
  • 61
-1

Using this test for perfect squares:

def is_square(n):
    for b in range(n):
        n -= (2 * b + 1)
        if n <= 0:
            return not n

... you can find those that appear in a with a simple list comprehension:

>>> [n for n in a if is_square(n)]
[4, 16, 144]
Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
  • perfect thanks.. @Zero Piraeus – Narendra Mar 17 '17 at 06:52
  • 2
    That test for squares does *way* too much work. You should be able to determine when a number is perfect square without looping over a large number of candidates. – Raymond Hettinger Mar 17 '17 at 06:53
  • Yeap this is point sir @RaymondHettinger but for every number how to check this. – Narendra Mar 17 '17 at 06:59
  • 1
    @RaymondHettinger well ... yes. This was actually kinda tongue in cheek; it's obviously a homework assignment posted by someone who hasn't put the slightest effort in, so I impishly decided to go find an obscure perfect square test they could present and then be unable to explain. Now that it's accepted, I don't think I can delete it. – Zero Piraeus Mar 17 '17 at 07:00
  • 2
    @ZeroPiraeus I commend your impishness and creativity :-) Well played. – Raymond Hettinger Mar 17 '17 at 07:02