A positive integer x is a perfect square if %u221A x is also an integer. For exa
ID: 3538782 • Letter: A
Question
A positive integer x is a perfect square if %u221A x is also an integer. For example, 1, 4, 9, 16, 25, 36, 49, 64, 81, and 100 are the perfect squares in the range 1 through 100. Write a function called perfectSquares1 that takes as parameter a list L of integers and returns a list consisting of all the elements of L that are perfect squares. For example, if L is [11, 9, 19, 250, 100, -9], then perfectSquares1 should return the list [9, 100]. The order of the elements in the returned list is not important. The algorithm you should use for perfectSquare1 is the following. First find the maximum integer in L. Call this m and generate the list L1 of the squares of numbers from 1 through floor(%u221A m ). You should use the function squares from Problem 1 to do this. Finally, perfectSquares1 should return all integers in L that are also in L1.
so far i have made a function that will return the perfect sqaure root of a number
def sqrt(x):
ans = 0
if x>=0:
while ans*ans < x : ans+=1
if ans *ans != x:
print(x ,'is not a perfect square')
return None
else :
return ans
else:
print(x , ' is a negative number')
return None
return ans
def main():
print(sqrt(100))
main()
i am having issue with list part
Explanation / Answer
def sqrt(x):
ans = 0
if x>=0:
while ans*ans < x :
ans+=1
if ans *ans == x:
return ans;
return -1;
def main(l):
i=0
list=[]
while(i<len(l)):
if(sqrt(l[i])!=-1):
list.append(l[i])
i=i+1
return list
l=main([1,3,9,16,24,25,29,60])
print l
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.