Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

recursive function to add digits in python fails when leading digit is zero

I'm trying to create a recursive function that adds all the digits in a number. Here's what I've come up with:

def sumOfDigits(num):
    num=str(num)
    if len(num)==0:
        return 0
    elif len(num)==1:
        return int(num)
    elif len(num)>1:
        return int(num[0]) + int(num[-1]) + int(sumOfDigits(num[1:-1]))

this seems to work for almost any number:

sumOfDigits(999999999)
>>>81
sumOfDigits(1234)
>>>10
sumOfDigits(111)
>>>3
sumOfDigits(1)
>>>1
sumOfDigits(0)
>>>0

strange things happen though if the number begins with '0'

sumOfDigits(012)
>>>1
sumOfDigits(0123)
>>>11
sumOfDigits(00010)
>>>8

what am I missing here??

like image 861
Pav Ametvic Avatar asked Jul 25 '26 00:07

Pav Ametvic


1 Answers

In Python 2, integer literals that start with zero are octal.

To take your examples:

In [46]: 012
Out[46]: 10

In [47]: 0123
Out[47]: 83

In [48]: 0010
Out[48]: 8

Since your function works in base ten, it is doing its job correctly. :)

As an aside, you need neither string manipulation nor recursion for this problem. Since others have already suggested non-recursive solutions, here is a recursive one that doesn't use string manipulation:

def sumOfDigits(n):
   return 0 if n == 0 else sumOfDigits(n // 10) + n % 10
like image 66
NPE Avatar answered Jul 28 '26 16:07

NPE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!