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

Asokan Pichai pasokan at talentsprint.com
Tue Dec 10 11:36:49 CET 2013


On Tue, Dec 10, 2013 at 3:09 PM, Rafael Knuth <rafael.knuth at gmail.com>wrote:

> Hej there,
>
> > I don't know if everyone would consider this more elegant but it's
> > certainly shorter:
>
> Thanks!
>
> >>>> def DigitSum(YourNumber):
> > ...     return sum(map(int, YourNumber))
> > ...
> >>>> DigitSum('55')
> > 10
>
> I don't understand yet what the "map" function does - can you explain?
> I read the Python 3.3.0 documentation on that topic but I frankly
> didn't really understand it
> http://docs.python.org/3/library/functions.html#map. My search for
> simple code examples using "map" wasn't really fruitful either.
>
> Other than that, I went through each of the 7 alternatives to my
> "Integer to Digit Sum" program you guys sent me, I understand what
> each of those programs does. My favorite one is:
>
> def DigSum (integer):
>     s = 0
>     while integer != 0:
>         integer, remainder = divmod(integer, 10)
>         s += remainder
>     print(s)
>
> DigSum(537)
>
> It's really a beautiful, elegant solution IMHO and way better than my
> original code (convert int to string, store each digit in an empty
> list, then convert them back to int and sum them).
>
> 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


> Again, thank you all!
>
You are welcome.


Asokan Pichai

"So, if I look into my foggy crystal ball at the future of computing
science education, I overwhelmingly see the depressing picture of "Business
as usual". The universities will continue to lack the courage to teach hard
science, they will continue to misguide the students, and each next stage
of infantilization of the curriculum will be hailed as educational
progress."

Edsger W Dijkstra in Dec 1988, in an article titled "on the cruelty of
really teaching Computer Science" Link:
http://www.cs.utexas.edu/~EWD/transcriptions/EWD10xx/EWD1036.html
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20131210/2d012e00/attachment-0001.html>


More information about the Tutor mailing list