4/15 What is the problem?


Why is this wrong?

def digit_sum(n):
listt = []
for hi in n:
return listt
total = 0
for h in listt:
total += int(h)
return total


on second line when you call str(n) you have to store it in a variable and the use that variable. Because you don't store it in a variable the type of the argument n passed is not changed which will give you an error because an integer is not an iterable
Also remember when you call return in a method the method terminate(i.e. we are done with the method) so your method will terminate after the first return and whatever follow is unreachable

with all that is said an done. you can modify your code to this

def digit_sum(n):
    n = str(n)
    sum = 0
    for i in n:
        sum += int(i)
    return sum
print digit_sum(233)

You can also use lists (maybe a bit overkill and unnecessary but try it just for practice) to solve this


That is far to many lines to accomplish this. You can honestly get this down with 2 lines with list, list comprehension, and the built-in sum function. Here are some helpful things to remember. You can convert the input to a list with:
nums = [int(x) for x in str(x)]
now you have nums as a list of the digits of your input
You can now use the built in sum function
return sum(x for x in nums)


@chullcse that is one way to go but going by your implementation as explained this is what we get

def digit_sum(number):
    # i replaced the value of nums in the sum() call
    return sum(x for x in [int(x) for x in str(number)])

This is a great implementation but there is one part that you must get rid of because it is a repeat of what is already done (you have two for loops doing the same thing).You can reduce the implementation to this

def digit_sum(number):
    return sum(int(x) for x in str(number))

def digit_sum_2(number):
    return sum([int(x) for x in str(number)])

Another alternative is to use lambdas to solve this like below

def digit_sum(number):
    #for python3.x users
    #import functools
    return reduce(lambda x,y:x+y, [int(x) for x in str(number)])

Click here to go to labs


That is true. Better simplified with just
return sum([int(x) for x in str(number)])

I just saw what I wrote. Could have been just a one-liner. Good catch!