Python code simplification? One line, add everything to the list

I am making my way through the Euler project, and I am trying to write the most concise code I can. I know this is possible, as I can simplify the following code. Preferably, I would like it to be a single line and not use the conversion int-> string-> int.

Question: What is the sum of the digits of 2 1000 ?

My answer:

>>> i=0 >>> for item in [int(n) for n in str(2**1000)];i+=item 
+6
python
source share
3 answers
 sum(int(n) for n in str(2**1000)) 
+16
source share

Not a one-line, but cleaner generator solution, also avoiding the conversion int-> string-> int:

 def asDigits(n): while n: n,d = divmod(n,10) yield d print sum(asDigits(2**1000)) 

Gives 1366.

Interestingly, the sum of the digits in 2 ** 10000 is 13561, the digits of which are the same value as 1366.

Of course, if expressed in binary terms, the sum of the digits in 2 ** 1000 is 1. (I even did it in my head!)

+3
source share

Single int to str conversion to get length:

 int(sum(map(lambda x:2**1000/x % 10, (10**x for x in xrange(len(str(2**1000))))))) 
0
source share

All Articles