On 2011-09-16, Gary Herron <gher...@digipen.edu> wrote: > On 09/16/2011 01:17 PM, Arnaud Delobelle wrote: >> On 16 September 2011 21:06, Ian Kelly<ian.g.ke...@gmail.com> wrote: >>> On Fri, Sep 16, 2011 at 1:21 PM, zombie<thatiparthysreeni...@gmail.com> >>> wrote: >>>> Hi guys, >>>> i am writing a program to sum up the digits of a number 2**1000? >>>> Is there a way/formula to do it without expanding it? >>> Possibly, but why worry about it? It's only around 300 digits. >>> >>> Since this sounds like homework, I won't post the one-liner I used to >>> do it the brute-force way, but I will note that it takes about 200 >>> microseconds to run on my laptop. >> Ah go on, let's make a codegolf contest out of it. >> My entry: >> >>>>> sum(map(int,str(2**1000))) >> 1366 >> > > Here's another one-liner using a generator instead of map: > > sum(int(c) for c in str(2**1000))
Just in case you can't spare the 3KB required for the list of integers that map creates. :) In this case it doesn't matter, but it's not hard to find problems where the difference between the memory requirements for a generator and a map/list-comprehension are significant enough to worry about. -- Grant -- http://mail.python.org/mailman/listinfo/python-list