Home > OS >  Please help me solve this algorithm im in problem this code python (TypeError: 'NoneType'
Please help me solve this algorithm im in problem this code python (TypeError: 'NoneType'

Time:12-09

it is my first post in StackOverflow I'm having trouble understanding and applying this exercise on my own with python please could help me! getting this TypeError: 'NoneType' object is not iterable

This is the exercise Algorithm:

Definition: An integer is said to be perfect if it is equal to the sum of all its divisors. Examples: 6 and 28 are perfect since
  6 = 1 2 3 (knowing that 1, 2 and 3 are the divisors of 6 less than 6)
28= 1 2 4 7 14 (knowing that 1, 2, 4, 7 and 14 are the divisors of 28 less than 28)
1) Create a function liste_divisors(), which accepts an integer N as a parameter and returns the list of its divisors less than N (1 included).

2) Make a function is perfect(), which accepts a (positive) integer N as a parameter and returns “True” if it is perfect and “False” otherwise (use the function from the 1st question)

3) Create a Perfect List() function, which accepts a Limit parameter, then returns a list containing the perfect numbers less than Limit

This is my attempt so far, but there are errors, please help me to correct these errors and make it better

def liste_diviseur(N):
   for i in range(1,N):
      if(N%i == 0):
         print(i)

def est_parfait(M):
   s = 0
   for i in liste_diviseur(M):
      s  = i 
   if(s == M):
      return True
   else:
      return False

def liste_parfait(Limite):
   if(Limite<est_parfait(Limite)):
      return Limite
m = int(input('Giving an number :'))
print(liste_parfait(m))

CodePudding user response:

As you iterate over the result of liste_diviseur() this latter function must return an iterable (something we can iterate).

It can be a sequence : a list or a tuple.

def liste_diviseur(N):
   diviseurs: list[int] = []
   for i in range(1,N):
      if(N%i == 0):
         print(i)
         diviseurs.append(i)
   return diviseurs

Or simpler you can use a Generator.

def liste_diviseur(N):
   for i in range(1,N):
      if(N%i == 0):
         print(i)
         yield i

Consider adding N itself to the divisors list. N divided by N equals 1. You can add N at the end of the loop. Or you can have a higher range with range(1, N 1) as the upper bound is not comprised.

CodePudding user response:

"1) Create a function liste_divisors()....and returns the list of its divisors.."

Your function just prints the divisors, You need to collect them in a list and return it.

Then you can iterate over the list in est_parfait(M).

  • Related