Using Multiple Recursive functions in Python

I am computing sum of digits of a number recursively, until sum is less than 10. For example;


Since final sum of digits is 9, then we stop. I am aware of following recursive approach which works fine, in my knowledge;

First Approach

def sumdigits(n):
    if n//10==0:
       return n
    return sumdigits(q+r)

But I am trying to write it using two recursive functions, in order to learn a different approach. Here is my second approach;

Second Approach

def digitalRoot(n):
    def sumdigits(n):
        if n==0:
            return 0
        return r+sumdigits(q)
    if s//10==0:
       return s
    return r+sumdigits(q)

As seen, I am trying to write a separate check whether sum of digit is less than 10. It is working for situations where the level of calculation is at most 2. For example n=99999 gives the sum as 99999->45->9.

But if we have case like n=27640, the correct output she be 1, since 27640->19->10->1. But my code is stopping at second level and giving answer as 10. Can I get some help to modify my second code so as to fix the issue? Thanks in advance.

3 answers

  • answered 2020-10-16 04:48 Hans Musgrave

    The problem is that you're only ever computing at most two levels. At no point have you encoded the logic that says "and do this till we get an answer less than 10." So...let's do that.

    def sum_digits(n):
      t = 0
      while n:
        n, r = divmod(n, 10)
        t += r
      return t
    def digital_root(n):
      while n >= 10:
        n = sum_digits(n)
      return n

  • answered 2020-10-16 05:20 python_learner

    There is an iterative solution already provided by Hans that does what you want, here is a recursive approach.

    You are doing it right but like Hans pointed out "At no point have you encoded the logic that says "and do this till we get an answer less than 10."". Just added that condition to what your code already did.

    def sum_digits(num):
        Returns the sum of individual digits in a number
        eg: 123 -> 1+2+3 -> 6
        if num<10:
            return num
        return r+sum_digits(q)
    def sum_till_single_digit(num):
        Does `sum_digits` recursively till the sum is a single digit
        eg: 99 -> 9+9 -> 18 -> 1+8 -> 9
        if num<10:
            return num
        return sum_till_single_digit(sum_digits(num))
    print(sum_till_single_digit(27640)) # 1

  • answered 2020-10-16 15:29 Alain T.

    You can use sum() and map() to obtain the sum of digits from the string version of the number.

    Then the recursion simply needs to check if the result is less than 10:

    def numerologic(n):
        s = sum(map(int,str(n)))
        return s if s<10 else numerologic(s)

    or on a single line:

    def numerologic(n): return n if n<10 else numerologic(sum(map(int,str(n))))