Question on 4/15


I had some difficulty understanding how the answer,
def digit_sum(x):
total = 0
while x > 0:
total += x % 10
x = x // 10
print x
return total

was derived from the instruction set,
“Write a function called digit_sum that takes a positive integer n as input and returns the sum of all that number’s digits. For example: digit_sum(1234) should return 10 which is 1 + 2 + 3 + 4. (Assume that the number you are given will always be positive.)”

I understand how to start off a definition. After that, I am lost. Anyone care to break it down “dummy style” for me? Thank you in advance!


You’ve kind of answered your own question…

Above you have added the numerical values of a number of objects expressed as a single expression. The function you posted is mathematical and sums the last digit as the number is divided by 10 and rounded to an integer (floor divided).

Add the last digit to the accumulator.

Floor divide x. 113 becomes 11.


Okay, thank you. I am going to look this one over again. Maybe its the floor divide that is throwing me off. Haven’t covered this one yet.


When we think in number types, floor divide is essentially rounding down to the nearest integer any quotient.

11 // 5  =>  2

What is 1234 mod 10?

1234 % 10  =>  4

We add that to the total and remove the number from the representation that is to passed forward.

1234 // 10  =>  123

Now repeat the above, and after, this step. Return the total when the number is dissolved.

And there are cheaper and dirtier,

>>> from functools import reduce
>>> reduce(lambda a, b: int(a) + int(b), str(1234))


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