I'm making my way through project Euler and 开发者_Python百科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
sum(int(n) for n in str(2**1000))
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!)
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)))))))
精彩评论