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