Digit_sum - completed but need review


#1

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):
    score=0
    count=len(str(n))
    while count>0:
        last=n%10
        n=n/10
        score=score+last
        count=count-1
    return score

Thanks a lot.


#2

Here's my version:

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

#3

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

#4

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


#5

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.


#6

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:


#7

Here's my version:

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

#8

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


#9

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

#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:


#11

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.


#12

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):
holder.append(int(i))
return sum(holder)


#13

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