Most efficient way to add together numbers within an integer?


Is this the most efficient way to answer this question or is there a simpler way to do it?

def digit_sum(n):
    n = str(n)
    sum = 0
    count = 0
    for i in n:
        sum = sum + int(n[count])
        count += 1
    return sum


What I used to solve this lesson is as follows:

def digit_sum(n):
        b = []
        n = str(n)
        for a in n:
                a = int(a)
        return sum(b)
        print sum(b)

Your method certainly works. If you see my code, I used a list instead, because it worked for me, but I don't think there's really much else you need to do.


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