I am trying to write a generator with class thats gets a list of numbers and, for each number, return true
if the sum of the divisors of this number is greater than the number and false
if not.
sum_of_divisor_helper
is a helper function.
Unfortunately I am getting this error:
Traceback (most recent call last): File "main.py", line 33, in for i in numbers: File "main.py", line 23, in next if (sum_of_divisor_helper(self.list1[self.x]) == True): NameError: name 'sum_of_divisor_helper' is not defined
This is the code:
class sum_of:
def __init__(self,myList):
self.x = 0
self.list1 = myList
def __iter__(self):
return self
def sum_of_divisor_helper(self):
sum_of_divisors = 0
for i in range(1, self.x):
if self.x % i == 0:
sum_of_divisors = sum_of_divisors + i
else:
pass
if sum_of_divisors >= self.x:
return True
else:
return False
def __next__(self):
if sum_of_divisor_helper(self.list1[self.x]) == True:
return True
self.x = self.x + 1
elif sum_of_divisor_helper(self.list1[self.x]) == False:
return False
else:
raise StopIteration
numbers = sum_of([12,20,10,30])
for i in numbers:
print(i)
Try
self.sum_of_divisor_helper(self.list1[self.x])
instead of
sum_of_divisor_helper(self.list1[self.x])
Use the self
prefix when you're referring to a method inside of your class.