Lesson in debugging of your approach - there are better ones:
def sum_divisors(n):
sumlist = []
for i in range(n ,0 , -1):
if n % i == 0:
sumlist.append(i)
# n -= 1 # this does nothing valuable
# elif n % i != 0: # this does nothing
# pass # this does nothing
fsum = sum(sumlist)
# debugging what your func computes by printing it:
print (n, sumlist, fsum, sep = " ==> ")
return fsum
sum_divisors(0) # sum of 0 = 0
sum_divisors(3) # Should sum of 1 = 1
sum_divisors(36) # Should sum of 1+2+3+4+6+9+12+18 = 55
sum_divisors(102) # Should be sum of 2+3+6+17+34+51 = 144 (wrong sum)
Outputs:
0 ==> [] ==> 0
3 ==> [3, 1] ==> 4
36 ==> [36, 18, 12, 9, 6, 4, 3, 2, 1] ==> 91
102 ==> [102, 51, 34, 17, 6, 3, 2, 1] ==> 216
According to what you want as result - you start to test your range with n-1
instead of n
to get there:
def fixed_sum_divisors(n):
sumlist = []
for i in range(n-1 ,0 , -1): # dont start with n
if n % i == 0:
sumlist.append(i)
fsum = sum(sumlist)
print (n, sumlist, fsum, sep = " ==> ")
return fsum
fixed_sum_divisors(0) # sum of 0 = 0
fixed_sum_divisors(3) # Should sum of 1 = 1
fixed_sum_divisors(36) # Should sum of 1+2+3+4+6+9+12+18 = 55
fixed_sum_divisors(102) # Should be sum of 2+3+6+17+34+51 = 144 (wrong sum)
Output:
0 ==> [] ==> 0
3 ==> [1] ==> 1
36 ==> [18, 12, 9, 6, 4, 3, 2, 1] ==> 55
102 ==> [51, 34, 17, 6, 3, 2, 1] ==> 114 # your 144 is wrongly summed up