Issue
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
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)
Answered By - Moris Huxley
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.