Yesterday I wrote about Code Wars, one of my favorite programming challenge sites. If you want to get better as a programmer, or are learning how to program check out my introduction and get signed up.
It is completely free!
I recommend doing at least one challenge a day as a routine after you get started, it will help keep you learning and solving real world problems. I started a new account and doing the same thing myself.
Today's challenge
def square_digits(num):
pass
As I mentioned in my Code Wars introduction, you want to break your problems into smaller problems. In fact, get as small as you can.
This challenge involves a few things.
- Iterate digits of a number
- Square a number
- Concatenate result
Let's start with the first problem. As an integer is not iterable, we need to convert the input number to a string.
def square_digits(num):
for digit in str(num):
pass
The second problem we need to solve is how to square the digits.
def square_digits(num):
output = ""
for digit in str(num):
output += str(int(digit) ** 2)
In this step we are able to solve both problem #2 and problem #3 as we are going to build a string as we iterate each digit.
We first needed a new variable to store the output as we iterate each digit.
We had to cast the digits between str and integer to make this work. First, we needed to convert digit (string) to an integer so we could use the power operator (**) and square the digit. We then had to convert it to a string again to store it in the output (string) variable. We are using the output variable to easily concatenate the output using native string functionality.
Finally we need to return the result, a simple return output
wouldn't work as the challenge is expecting an integer, so we need to cast it as an integer.
def square_digits(num):
output = ""
for digit in str(num):
output += str(int(digit) ** 2)
return int(output)
Let's test our solution.
Looks good! I submitted the solution and reviewed the best answers.
The first answer is extremely similar to our solution, so I am happy that we have a good solution.
The second solution is smaller, more compact, and very clever but considerably harder to read. Being clever is not always a good thing, it's ok to be clever in your algorithms and logic, but being clever with syntax generally results in difficult to read code.
I challenge you to sign up for Code Wars, pick your favorite languages and do your own challenges.
If you like this series, let me know in the comments and I will do more.
