4. another digit_sum using % and / (more laconic)


#1



Is it good version???


def digit_sum(n):
    total = 0
    while n > 0:
        total += n%10
        n = (n - n%10)/10
    return total


#2

this line:

n = (n - n%10)/10

you could simply divide n by 10:

n = n / 10

why n - n%10?

to be certain, i would use floor division (//) to make sure you don't end up with decimal number which might make your loop run longer then needs be


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.