[Tutor] Converting integers into digit sum (Python 3.3.0)

Oscar Benjamin oscar.j.benjamin at gmail.com
Mon Dec 9 11:16:25 CET 2013


On 9 December 2013 08:08, Rafael Knuth <rafael.knuth at gmail.com> wrote:
> Hej there,
>
> I wrote a program that converts an integer into a digit sum:
>
> 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 of converting an integer into a digit sum?  I learned from
> past conversations on this mailing list that often times there is a
> better, more elegant and shorter way to write a program, and I was
> wondering if that's the case here.

I don't know if everyone would consider this more elegant but it's
certainly shorter:

>>> def DigitSum(YourNumber):
...     return sum(map(int, YourNumber))
...
>>> DigitSum('55')
10


Oscar


More information about the Tutor mailing list