0

I'm a novice when it comes to recursion (and python, be kind haha), so I wanted to give it a go with a codewars problem (https://www.codewars.com/kata/541c8630095125aba6000c00/train/python)

I'm just super confused as to why the break gets ignored, and the recursion continues.

def digital_root(n):
    x = list(str(n))
    z = 0
    while True:
        for i in range(0, len(x)):
            x[i] = int(x[i])
        for i in x:
            z = i + z
        if z < 10:
             break
        elif z >= 10:
            digital_root(z)
    return z

print(digital_root(942))
1
  • In your example, the break is met when z<10, which means previous z + all values of x less than 10, i.e, previous z < -5, but that's impossible using your current code Commented Sep 15, 2020 at 3:02

1 Answer 1

2

After calling itself recursively, it's discarding the return value, so z and x remain unchanged. Change the recursive call to:

return digital_root(z)

That way the recursion will end. In fact, the while loop should never execute more than once, so you could just do:

def digital_root(n):
    x = list(str(n))
    z = 0
    for i in range(0, len(x)):
        x[i] = int(x[i])
    for i in x:
        z = i + z
    if z < 10:
        return z
    return digital_root(z)

Or, if you'd rather eliminate the recursion entirely, all you really need is the following (which includes some additional simplifications):

def digital_root(n):
    while n >= 10:
        n = sum(int(d) for d in str(n))
    return n
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I appreciate it! I did end up solving it similar to the way you mentioned. I just wanted to force recursion for practice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.