0

Given n, take the sum of the digits of n. If that value has more than one digit, continue reducing in this way until a single-digit number is produced. This is only applicable to the natural numbers.

def digital_root(n):
    sum = 0
    print(n)
    lst = list(str(n))
    for num in lst:
        sum += int(num)
    if len(str(sum)) > 1:
        digital_root(sum)
    else:
        return sum
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • digital_root(14) gives 5 correctly but when my function uses the recursion, let's say digital_root(191), it gives None instead of the correct answer(2 in this case) – Milind Bebarta Jun 05 '20 at 09:24
  • I just ran your program in my jupyter notebook, it's working fine for me it seems. Gave the output 11 for 191. – monte Jun 05 '20 at 09:29
  • 1
    you dont return inside the if. When you dont return from a function by default it gives none. So change `digital_root(sum)` to `return digital_root(sum)` – Chris Doyle Jun 05 '20 at 09:31
  • Does this answer your question? [python recursion return None type](https://stackoverflow.com/questions/15340281/python-recursion-return-none-type) – bruno desthuilliers Jun 05 '20 at 09:45

1 Answers1

0

You can try;

>>> def digital_root(n):
...     sm = sum(int(x) for x in str(n))
...     if (sm > 9): return digital_root(sm)
...     else: return sm
... 

Here in the recursion case a return is added to return the result

Praveen
  • 8,945
  • 4
  • 31
  • 49