Digit_sum


#1



Can anyone please explain me why my code is not working? I get an error: Your function fails on digit_sum(434). It returns None when it should return 11.
What is wrong? It also doesn't print the sum of 123 when I input in the function


def digit_sum(n):
    total=0
    for i in range(len(str(n))-1):
        lastnum = n%10
        total = total + lastnum
        n = n/10
        
print digit_sum(123)


#2

you need to return the total


#3

Thank You! Got it:grin:


#4

i personally don't understand why you would want to do:

for i in range(len(str(n))-1):

this is not a very efficient loop condition. It needs to convert to string every iteration of the loop. (converting to string -> expensive operation)

with the solution you are going with, it makes more simply check while n is greater then 0 (math is much cheaper operation), given n will become zero at some point thanks to n = n/10


#5

Yeah! You are right. My code looked clumsy to me at first too. Also I need to change that condition to len(str(n)) to make it work. The code somehow also works if I just use for i in range(n). (no idea why)

while n>0 is more efficient! will keep this in mind next time


#6

that shouldn't work, if you want to get the digit sum of 456, range will give you 0,1 and 2

yes, in particular with the solution you are going with. Now there is no string conversion, only math, and that is fast :slight_smile:


#7

Can someone explain the n = n//0? I don't understand how it is connected to the rest of the code. I tried adding prints to my code to see what was happening at each stage but nothing printed. Also how did the number get converted back to an int from the strings?


#8

you mean n = n // 10? its floor division, n will divided by 10 and then round down to the nearest integer value.

it doesn't, we only use integers in this solution. No strings involved.

next time, please don't hijack the topic, rather create a linked topic as recommended in the guidelines


#9

The range(len(str())) made me think it was a string.
Sorry, there was a topic in the archives that matched what I was talking about but it was closed. I will start another one next time.


#10

there was, but then we got rid of it to get a more effective solution

you can start linked topics from closed topics, you can click the share button, and then select: create new topic, which will create a linked topic, the share button is in this guide:

the reason we close topics is so people make new topics/linked topics, this will keep the forum more organized


#13

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