[Tutor] Converting integers into digit sum (Python 3.3.0)
Wolfgang Maier
wolfgang.maier at biologie.uni-freiburg.de
Tue Dec 10 13:00:19 CET 2013
Asokan Pichai <pasokan <at> talentsprint.com> writes:
>
> If you liked it, I will give you one that uses one less variable
>
> def digitSum(n):
> dsum = 0
> while n > 0:
> dsum += n % 10
>
> n /= 10
> return dsum
>
> Stupid of me not to have mentioned that this Python 2.x only. Sorry
>
but very easy to fix:
def digitSum(n):
dsum = 0
while n > 0:
dsum += n % 10
n //= 10 # explicit floor division works in Python2 & 3
return dsum
Best,
Wolfgang
More information about the Tutor
mailing list