[Tutor] Converting integers into digit sum (Python 3.3.0)
Alan Gauld
alan.gauld at btinternet.com
Mon Dec 9 12:04:20 CET 2013
On 09/12/13 08:08, Rafael Knuth wrote:
> def DigitSum(YourNumber):
> DigitList = []
> YourNumber = str(YourNumber)
> for i in YourNumber:
> DigitList.append(int(i))
> print(sum(DigitList))
>
> DigitSum(55)
> 10
>
> It actually works but I was wondering if that's the only way to solve
> the task
You can simplify the code by using a list comprehension but that's
really just doing the same thing more compactly.
The other way of doing it is to stay in the number domain and use the
divmod function to peel off the digits and add them.
>>> total, num = 0, 75
>>> num,rem = divmod(num,10) # num=7, rem = 5
>>> total = num + rem
>>>
For longer numbers you need to wrap that in a while loop but
you get the idea. However, converting to a string and back
is probably the simplest option.
HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list