Check For Perfect Squares In A List
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]
Solution 1:
Once approach is to build a predicate (a function returning true or false) and apply it with filter():
>>> defis_perfect_square(n):
returnround(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.
Solution 2:
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 ifmath.sqrt(x).is_integer()]
Solution 3:
You can try:
>>>square_list = []>>>a = [3, 4, 8, 16, 21, 58, 144]>>>defperfect_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]
Solution 4:
Using this test for perfect squares:
defis_square(n):
for b inrange(n):
n -= (2 * b + 1)
if n <= 0:
returnnot 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]
Post a Comment for "Check For Perfect Squares In A List"