[Python] Happy numbers

Photo by Amine M’Siouri from Pexels
If we take a number, and sum the square of its digits, and then continue this process with the new number, we will either arrive at 1, or we will loop endlessly in a cycle that repeats itself. Those numbers that eventually end up at 1 are called happy numbers.
Consider the number 19. If we square its digits and then add them together, we get:
12 + 92 = 82
Then again:
82 + 22 = 68
Continuing in this fashion, we get:
62 + 82 = 100
And Finally:
12 + 02 + 02 = 1.
Therefore we can say that 19 is a happy number. Now you know who you are inviting for your next party.
So, we want to write a function to check for happy numbers. Here is what the function will do in a nutshell:
- Receive a number and turn it into string
- Sum the square of the digits of the number
- If the resulting number is equal to 1, then it is a happy number.
- Else if we have not seen the result before (no cycle has formed) continue the process
- If a cycle is detected, then break the loop. The number is a sad number.
Let us run a quick test to see how much it takes for the function to calculate how many happy numbers are therebelow 1000:
Here is the result: