Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python code simplification? One line, add all in list

Tags:

python

I'm making my way through project Euler and I'm trying to write the most concise code I can. I know it's possible, so how could I simplify the following code. Preferably, I would want it to be one line and not use the int->string->int conversion.

Question: What is the sum of the digits of the number 21000?

My answer:

>>> i=0
>>> for item in [int(n) for n in str(2**1000)];i+=item
like image 714
backus Avatar asked Jun 29 '10 22:06

backus


2 Answers

sum(int(n) for n in str(2**1000))
like image 85
SilentGhost Avatar answered Nov 14 '22 21:11

SilentGhost


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

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, whose digits add up to the same value as 1366.

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

like image 44
PaulMcG Avatar answered Nov 14 '22 22:11

PaulMcG