-1

i tried to implement function that finds the digital root of a number(it is the recursive sum of all the digits in a number.) but for some reason it returned none if the function make a recursive call to itself

import functools
def digital_root(n):
  r=functools.reduce(lambda x,y:int(x)+int(y),list(str(n)));
  if r//10<1:
   return r
  else:
   digital_root(r)
steve
  • 311
  • 3
  • 10

3 Answers3

4

You aren't returning any value in the else clause, hence it gives None

def digital_root(n):
  r=functools.reduce(lambda x,y:int(x)+int(y),list(str(n)));
  if r//10<1:
   return r
  else:
   return digital_root(r)

A more readable form would be:

def root(n):
    d_sum = 0
    for i in str(n):
        d_sum += int(i)
    if dsum<10:
        return d_sum
    return root(d_sum)

Without recursion:

def root(n):
    while n > 9:
        n = sum(map(int, str(n)))
    return n
wim
  • 338,267
  • 99
  • 616
  • 750
Abhinav Mathur
  • 7,791
  • 3
  • 10
  • 24
2

In addition to the lack of return, you didn't look up the reduced, closed-form algorithm:

return 9 if (r % 9 == 0) else (r % 9)
# Parentheses are unneeded, but added for readability

The "old-school" name for digital sum was "casting out nines"; you take the number's modulo base b-1, where b is the original number base. 9 for decimal, 15 for hex, etc.

Prune
  • 76,765
  • 14
  • 60
  • 81
  • Nice workaround solution, based on maths. Not suitable for programming assignments though – Abhinav Mathur Oct 13 '20 at 21:08
  • 1
    That depends on the assignment specs. Recursion was given only as a definition of "digital root", rather than an implementation requirement. – Prune Oct 13 '20 at 21:10
  • I gave you a +1 for mentioning it, but that's not perfect (try with 189 for example). Happy 4000th answer! – wim Oct 13 '20 at 22:34
  • All multiples of 9 would've failed this approach. Added an edit to the answer for this case – Abhinav Mathur Oct 14 '20 at 04:50
1

I don't know exactly what you try to achieve, but I guess that you would like to return the outcome of your recursive call, so change the last line of your example to:

   return digital_root(r)
Jan-Hein
  • 68
  • 6