0

I was solving a problem on Codewars involving recursion and I've never really done it before but kinda understand the concept. Im not really good at math stuff so it probably explains why I cant wrap my head around this. Essentially I think I kinda did the loop right I just dont know how to print the final value. Anyway heres my code:

def digital_root(n):
    newn = 0
    list = [int(x) for x in str(n)]
    if len(list) >= 2:
        for i in range(len(list)):
            newn += list[i]
        digital_root(newn)
    return n

print(digital_root(1234) 

output:

1234
r_33
  • 29
  • 5
  • The result of the inner call must be `return`ed explicitly by the outer function. – Michael Butscher Oct 17 '20 at 03:43
  • @MichaelButscher Thankyou for your reply. I understand I'm supposed to do that but I don't really know. I tried making newn a global but got a typeval error – r_33 Oct 17 '20 at 03:45
  • You return the result from a recursive call to your function *the same way that you would return the result from calling any other function*. – Karl Knechtel Oct 17 '20 at 03:47
  • You should show the alternative try and the full error message in the question. – Michael Butscher Oct 17 '20 at 03:49
  • There is no such thing as "a recursion loop". If you want to loop, use a loop - such as `while`. Recursion is a different way of thinking about the problem. – Karl Knechtel Aug 13 '22 at 00:42

1 Answers1

0
def digital_root(n):
    newn = 0
    list = [int(x) for x in str(n)]
    if len(list) >= 2:
        for i in range(len(list)):
            newn += list[i]
        return digital_root(newn) # You need to return it over here
    return n

print(digital_root(1234))
abhigyanj
  • 2,355
  • 2
  • 9
  • 29
Divyessh
  • 2,540
  • 1
  • 7
  • 24
  • this outputs `1234` again... – r_33 Oct 17 '20 at 03:47
  • @r_33 no this outputs 1 – Divyessh Oct 17 '20 at 03:49
  • hmm wait so I dont understand why this reoccurs. When your write `return digital_root(newn)` where does that output go back to? – r_33 Oct 17 '20 at 03:56
  • then it will return the value that will be obtained by `digital_root(newn)` for example in 1234 first it sums 1+2+3+4 = 10 then again sums 1+0 = 1 and return final value that is 1 – Divyessh Oct 17 '20 at 03:58
  • Oh I see. Thankyou. Is the way I went about solving this problem a bad/dumb way of doing so? – r_33 Oct 17 '20 at 04:00
  • No this is a really common mistake that probably everybody faces while beginig with programmin. If my answer helped please upvote it . – Divyessh Oct 17 '20 at 04:05