4. digit_sum mathematical solution for the task


#1



Hello, guys! I would like to hear your opinion about the solution for this task I am struggling to make. I am sure that is not the easiest way what I am trying to do, but I would love to accomplish this task using mathematics (I remember similar task when I was in High School, however now I can't do that same way).

  1. digit_sum


So, basically what I am trying to achieve is to represent an integer in the following shape:
n= 10^(i)n1+10^(i-1)n2+...+10^0*nj
where sum=n1+n2+...+n(j)


    sum=0
    n_len=len(str(n))
    i=n_len
    while i<=(n_len) and i!=1:
        digit=n//(10**(i-1))
        #Here is I can't really figure out the next iteration...
        #Maybe it's better to use exponent here
        return n, sum
        i-=1
        if i==1:
            sum+=n % (10**(i-1))
    return sum

print digit_sum(434)



Please, I am sure you guys know the solution. I won't be able to sleep unless I find the way :sleepy:


#3

What you are looking for can be boiled down.

def digit_sum(n):
    s = 0
    # what must we start with?
    # ans: a modulo
    while n > 0:
        s += n % 10     # the last digit
        # and go with?
        n //= 10         # the remaining digits without it (edited)
    return s

#4

Thank you!
This works great.
See below executing code that works in a case someone else want to solve this task old fashioned way.

def digit_sum(n):
    s = 0 
    i=len(str(n))
    while i>0:
        s+=n % 10     # the last digit
        print s
        n=n // 10       # the remaining digits without it
        i-=1
    return s
print digit_sum(4254)

#5

Sorry for my typo. Please see the edit:

n //= 10

#6

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