Digit_sum - completed but need review


I am interested in yours opinions. I wanted to complete the task without converting n into a string.
What do you think? Can it be completed simplier or tidier?

def digit_sum(n):
    while count>0:
    return score

Thanks a lot.


Here's my version:

def digit_sum1(n):
    result = 0
    while n>0:
        result += n%10
        n = n//10
    return result


This will end in an infinite loop. I tried this and had that problem. Here is my version of code:

> def digit_sum(n):
>     total = 0
>     x = n
>     while x > 0:
>         rem = x%10
>         total = total + rem
>         quo = x//10
>         x = quo
>         if rem == quo:
>             break
>     return total


No, it won't. Copy it and try for yourself.


digit_sum can be expressed as the composition of two functions: digits, and sum. A sum function already exists, so what remains to implement is a digits function and a compose function that takes two functions as input and returns a new function which applies both those functions to its argument.

Arguably it would be overall simpler to do it all in one function, but then again, this is very nice:

digit_sum = compose(sum, digits)

It only takes a glance to conclude that it's correct.
That digits function might be useful for other purposes as well. What about digit_product? (multiplication)

digit_product = compose(product, digits)

Python doesn't have a multiplication counterpart to sum, but it's still a nice idea.


It worked this time. Much simple code. I don't know what was the error I had when I tried this at first. That's why I had to create a much complex program :yum:


Here's my version:

def digit_sum(n):
    main = []
    for i in str(n):
    return sum(main)


This is much simple version by converting it to string and adding up the substrings. :slight_smile:


But is it to the computer? String operatons are notoriously slow. Math on the other hand has a dedicated chip to hep with the process.

x += n % 10
n //= 10


I totally agree to what you said. I just mentioned that the number of lines in the code is decreased when it's taken as a string :relaxed:


Take a number, convert it to a string, convert that to a list of integers, and sum it. A sensible approach but process intensive. The number of lines is the least of our concerns.


This won't work for digit_sum(1111) as it returns 3.

I refer @chamu33's solution (mine is essentially the same bar naming conventions):

def digit_sum(n):
holder = []
for i in str(n):
return sum(holder)


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