4 (digit_sum) - I don't understand what I'm doing wrong here


#1

This is my code:

array_of_digits = []

def digit_sum(n):
n = str(n)
for char in n:
x = int(char)
array_of_digits.append(x)
sum_of_digits = sum(array_of_digits)
return sum_of_digits

I keep getting a message that my code is wrong because digit_sum(1000) returns 12 when it should return 1. But when I call digit_sum(1000) and print the result, the console shows an answer of 1. Can anyone help me debug my code?


#2

You are making it too complicated and I can see where it would cause confusion.

Do this

def digit_sum(number):
    list_of_numbers = []
    for digit in str(number):
        list_of_numbers.append(int(digit))
    return sum(list_of_numbers)

While list comprehension is shorter and cleaner,

def digit_sum(number):
    return sum([int(digit) for digit in str(number)])