Most efficient way to add together numbers within an integer?


#1


https://www.codecademy.com/courses/python-intermediate-en-rCQKw/0/4?curriculum_id=4f89dab3d788890003000096#

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


#2

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)
                b.append(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.


#3

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