Recently, I was solving the Happy Numbers project from my Projects collection (a top repo on GitHub for a few weeks now). A major part of the problem was finding sum of square of digits of a number.
What I wrote initially was this:
def sum_digits(num):
sum_dig = 0
while num >= 0:
last_digit = num % 10 # extract the last digit
sum_dig += last_digit ** 2 # sum of square of digit
num /= 10 # strip of last digit
The problem was, it wasn't very pleasing to the eye!
But then I thought of this beautiful one-liner..
sum_digits = sum(int(digit) ** 2 for digit in str(num))
Elegant, isn't it?
What I wrote initially was this:
def sum_digits(num):
sum_dig = 0
while num >= 0:
last_digit = num % 10 # extract the last digit
sum_dig += last_digit ** 2 # sum of square of digit
num /= 10 # strip of last digit
The problem was, it wasn't very pleasing to the eye!
But then I thought of this beautiful one-liner..
sum_digits = sum(int(digit) ** 2 for digit in str(num))
Elegant, isn't it?
- Karan Goel
In your function sum_digits the while condition should be num > 0 otherwise it never finishes.
ReplyDeleteI wondered which approach was the fastest, so tested it. Then added some alternate approaches. Interestingly I also found that divmod is slower than doing two calculations yourself.
https://gist.github.com/stephenpaulger/6154551