Practice makes perfect - digit sum


#1

My code works for this exercise with less lines of code than the solution, but I am receiving
a message saying that my code failed. But that doesn’t seems to be true. Can someone help me understand this?

lac = []
def digit_sum(n):
y = str(n)
for item in y:
lac.append(int(item))
print sum(lac)


FAQ: Learn Python - Practice Makes Perfect - digit_sum
#2

your function prints the sum of the digits, it doesn’t return it


#3

The print was just to test if it was returning the right value.
If I print the total from the solution code, it does not show the right value (the sum of the digits).
Solution code…
def digit_sum(x):
total = 0
while x > 0:
total += x % 10
x = x // 10
print x
return total


#4

why would you add a print statement inside the function? Add a print statement + function call at the end of your script, bit redundant for the function itself to print and return.

x is not the value containing the sum of digits.

As for your solution, why do you also need a list? Then you have list, string and integers, bit much, no? sum() also under the hood uses a loop to get all values from list, do you really need two loops to solve the problem?


#5

That’s right. I used this non elegant list solution because I was not aware of these operators (% 10 and // 10). The current solution seems to be the best. But the line “print x” seems to be unnecessary.


#6

why?

even so, then i would have opted to declare a variable total before the loop, give it a value of zero and int(item) to total. Then we don’t need two loops to achieve the result. and we don’t need a list.


#7

Sure, I agree we don’t need the list. It’s unncessary to use lists and loops to solve this problem. 100% agreed.
But the “print x” is unncessary too.
This code below would be enough to check if the code works:

def digit_sum(x):
total = 0
while x > 0:
total += x % 10
x = x // 10
return total

print digit_sum(434)


#8

my bad, i thought you said necessary

yea, its unnecessary indeed.


#9

And you did the right thing. Finding your own solution is better than trying to figure out how somebody else’s solution works. We are expected to complete this unit from what we’ve learned so far.

As for the list, that is not necessary. A string is also iterable.

for x in str(n):
    total += int(x)

#10

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