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
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!)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With