'list of integer square roots python
Chances are this is a duplicate question but I've looked through the duplicate questions and I don't see an answer for python.
I'm trying to create a simple program where I can hard code a list of integers and filter out all the numbers that have integer square roots. Here's what I have so far:
# Python Program to display the number of integer square roots in a list
import math
# Change this list for testing
terms = [1,2,3,4,5,6,7,9,10,11,12,13,16,24,36]
all_roots = [] #list to hold all square roots from terms list
for i in terms:
all_roots.append(math.sqrt(i))
#integer_roots = list(filter(lambda x: [????], all_roots)) #not sure what I should put in the "[????]" part
print(all_roots) #prints integer and floating square roots
print(integer_roots) #supposed to print only square roots that are integers
To clarify, print(all_roots)
currently displays:
[1.0, 1.4142135623730951, 1.7320508075688772, 2.0, 2.23606797749979, 2.449489742783178, 2.6457513110645907, 3.0, 3.1622776601683795, 3.3166247903554, 3.4641016151377544, 3.605551275463989, 4.0, 4.898979485566356, 6.0]
But I want print(integer_roots)
to display
[1, 2, 3, 4, 6]
Solution 1:[1]
import math
terms = [1,2,3,4,5,6,7,9,10,11,12,13,16,24,36]
integer_roots = []
for i in terms:
tmp = math.sqrt(i)
if (tmp.is_integer()):
integer_roots.append(int(tmp))
print(integer_roots)
Solution 2:[2]
A list comprehension would help with a generator expression inside to prevent duplicate function calls:
>>> [int(i) for i in (math.sqrt(i) for i in terms) if i.is_integer()]
[1, 2, 3, 4, 6]
Or if you want a purely functional approach, since you suggest using filter()
in your post:
>>> list(map(int, filter(float.is_integer, map(math.sqrt, terms))))
[1, 2, 3, 4, 6]
Of course this can be written out with a regular for
loop, which is less performant but totally acceptable, particularly given the OP seems new to Python:
lst = []
for i in terms:
s = math.sqrt(i)
if s.is_integer():
lst.append(int(s))
Solution 3:[3]
import math arr = list(map(math.isqrt ,[1,2,3,4])) print(arr)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | |
Solution 3 |