Xayden Rosario
Xayden Rosario

Reputation: 177

I don't know why this while loop doesn't stop iterating

It's a challenge on codewars.com, but I can't figure out why this while loop doesn't work

def digital_root(n):
    # Creating variable combine to have the sum
    combine = 0
    # as long as n is more than two numbers.
    while n > 10:
        # converting n to string to iterate
        for i in str(n):
            # getting the sum each element in n
            combine += int(i)
        # reset n to be equal to the combined result
        n = combine
    return combine

also, any solutions will be appreciated, here is the link to the challenge https://www.codewars.com/kata/sum-of-digits-slash-digital-root

Upvotes: 0

Views: 85

Answers (3)

gzerone
gzerone

Reputation: 2227

interesting;)

def digital_root(n):
    return n if n < 10 else digital_root(sum(int(i) for i in str(n)))

Upvotes: 1

Wesley Bowman
Wesley Bowman

Reputation: 1396

I would do something like the following:

def digital_root(n):
    combined = 0
    while True:
        for i in str(n):
            combined += int(i)

        print combined

        # this is the condition to check if you should stop
        if len(str(combined)) < 2:
            return combined
        else:
            n = combined
            combined = 0

EDIT: you could also do it without converting to a str like you did:

def digital_root(n):
    combined = 0
    while True:
        for i in str(n):
            combined += int(i)
        print combined
        if combined < 10:
            return combined
        else:
            n = combined
            combined = 0

Upvotes: 0

CaptainMeow
CaptainMeow

Reputation: 351

It is nice that you are updating n, but what about combine. Perhaps a a reset is needed at the end of every iteration?

Upvotes: 0

Related Questions