简体   繁体   中英

Python code simplification? One line, add all in list

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 2 1000 ?

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

单个int到str转换以获取长度:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM