views:

205

answers:

4

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
+13  A: 
sum(int(n) for n in str(2**1000))
SilentGhost
For fun, this is the exact same thing:`sum(int(n) for n in str(1<<1000))`
jcao219
better to document the code, cos the next person who reads this would be like "WTF?"
James Lin
how is `sum(foo)` less readable than `x=0;for item in foo:x+=item;x` ?
Jimmy
for fun, sum(map(int,str(2**1000))) ;)
st0le
A: 

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)))))))
Kamil Szot
Generator expression?
chpwn
+3  A: 

One line. No string to int conversion. Also very fast:

>>> 1366

No need to down-vote this. It's just a joke.
jcao219
I guess someone didn't get the joke. :-)
Kamil Szot
upvoted because I got the joke
Aaron
Joke answers should probably be wiki'd
Davy8
+2  A: 

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!)

Paul McGuire