4. digit_sum Modulo Help



Hey guys,

I got frustrated using the str to int method (i couldn't get the split function to work) so I am trying the 'challenge' method involving using modulo to seperate digits and add them together.

I wrote a code that I think should work (at least for three digit numbers so far) but I receive an error:
"Oops, try again. Your function fails on digit_sum(434). It returns 7 when it should return 11."

Here's my code:

def digit_sum(n):
    first_digit = n % 10 
    a = n - first_digit
    second_digit = (a % 100)/10
    b = a % 100
    c = a - b
    third_digit = b / 100
    return first_digit + second_digit + third_digit

I apologize if it's confusing, but when I work out the code manually on paper I should get the intended answer.

Any ideas?

Thanks for the help!


Not sure why you'd want to split anything.. I think you might need to ask yourself what you'd gain and consider if you don't already have that without splitting.

To compute the sum of all digits, you will need to consider all digits. Right now you seem to consider three, regardless of how many there are.

If you wish to start with a non-general solution to just get the steps down, (I don't really agree with it but sure, not completely unreasonable) then you'll need to observe what it's doing differently from what you do with pen and paper/in your head. Make it print out what it's doing step by step and check that output.


2 posts were split to a new topic: 4. digit_sum


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