Solution Exercise 68: algorithm that determines the list of perfect squares

Sep 3, 2021

Exercise 68

Write a Python algorithm which determines for a given integer, the list of perfect squares between 1 and n. Example if n = 100 the algorithm returns the list

``[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]``

Solution

``# function which tests whether a number is perfect square or notdef perfectSquare(n):     # initialization counter     counter = 0         for i in range (1, n + 1):          if i * i == n:               counter = counter + 1     if counter > 0:          return True     else:          return False# function which determines the list of perfect squaresdef listPerfectSquare(n):     # initialization of the list of perfect squares     lperfect = []     for i in range (1, n + 1):          if perfectSquare(i):               lperfect.append (i)     return lperfect#Examplen = 100print (listPerfectSquare (n))# displays: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]``
Younes Derfoufi
my-courses.net