-1

Currently, I have written a recursive function to do sum_of_digits but it works for smaller numbers, e.g. Less than 6.

But for larger numbers, the calculation messes up for some reason.

def sum_of_digits(i):
    if i == 0 :
        return i
    else:
        return i % 10 + sum_of_digits(i / 10)

sum_of_digits(228475) 
# returns 31.111111111111107 
# should be returning 28 instead

What am I doing wrong here?

kraljevocs
  • 115
  • 1
  • 2
  • 12

4 Answers4

2

You need to use //, the integer division, instead of / (float division). Using / loses precision, which leads to the error you encounter.

def sum_of_digits(i):
    if i == 0:
        return i
    return i % 10 + sum_of_digits(i // 10)

print(sum_of_digits(228475)) # 28

And it can be done with:

print(sum(map(int, str(228475)))) # 28
j1-lee
  • 13,764
  • 3
  • 14
  • 26
1

You should use "integer division (operator //)" instead of normal division (operator /) in the 5th line.

...
        return i % 10 + sum_of_digits(i // 10)
...

Integer division return the largest integer that is no larger than the result of normal division. For example,

5/2 = 2.5    =>  5//2 = 2
-5/2 = -2.5  =>  -5//2 = -3
6/3 = 2.0    =>  6//3 = 2
Alex Chen
  • 53
  • 5
  • My bad. It should be "largest integer smaller than 'or equal to' the result of normal division". I have edited the answer. – Alex Chen Feb 17 '22 at 06:06
1

There are many solutions but if you are not comfortable with divisions and modulo(%), you can use this method. Just pass the Numer as a string into the function.

def sum_of_digits(num, ind=0):
    
    if ind == len(num):
        return 0
        
    return int(num[ind]) + sum_of_digits(num,ind+1)


sum_of_digits(str(228475))
#RESULT = 28
huzzzus
  • 172
  • 10
0

Try to cast your value to int type:

def sum_of_digits(i):
if i == 0 :
    return i
else:
    return i % 10 + sum_of_digits(int(i / 10))

print(sum_of_digits(228475)) 
benson23
  • 16,369
  • 9
  • 19
  • 38