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?
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