4.digit_sum : answers


I didn't know how to solve this problem, so searched, and this is the one I'm trying to understand.
I thought it would be nice to share. There are one way we can do based on what we learned at the codecademy, but another using 'map.'

link: http://stackoverflow.com/questions/16266130/how-to-get-digit-sum-in-python

You have to change it to a string first :

In [24]: num = 123456

In [25]: sum(int(x) for x in str(num))
Out[25]: 21

Without converting to a string:

def solve(n):
    while n:
        summ+= n%10
    return summ


In [38]: solve(123456)
Out[38]: 21

In [1]: num=123456

In [2]: sum(map(int,str(num)))
Out[2]: 21

In [3]: def digitsum(x):
   ...:     return sum(map(int,str(x)))

In [4]: digitsum(num)
Out[4]: 21


I am sorry. None of the two brings the right result in codecademy.
Maybe somebody can explain why?

Thank you!


Go here for my solution to the problem



Hi friends,

After quite a bit of try and error and searching, I found a relatively simple and understandable way to solve this:

def digit_sum(n):
    num= sum(map(int, str(n)))
    return num

Going through the Python docs makes the applied syntax clearer.



code for the challenge!
def digit_sum(n):
while n!=0:
countn += n%10
return countn


That worked for me:

def digit_sum(n):
        count = 0
        suma = 0
        n = str(n)
        z = len(n)
        print z
        while count < z:
            x = n[count]
            x = int(x)
            suma += x
            count += 1
            print count
            print suma
        return suma
        return count

import math
def digit_sum(n):
    print nstr
    for i in nstr:
    return summation


can somebody please let me know, what is wrong with the below code:
def digit_sum(n):
num_sum = 0
digits = len(str(abs(n)))
digits = int(digits)
while digits != 0:
last_num = n%10
num_sum = num_sum + last_num
digits -= digits
n = n // 10
return num_sum