Happy Number (Python)

How to determine if a number is happy (mathematically) ?

image source: w3resource.com
Now you get the definition, let's jump right in to coding.

Prerequisites:
Basics of Python (variables, if-else, functions, loops, classes, etc)

⚠⚠⚠ My code is not officially verified!

First step: define a function and add necessary parameters to it (for the time being let's add pass statement to avoid errors)

Second step: split the numbers to induvial digits

Third step: add up all the squares


Full version of line 3, in case you haven't learnt list comprehension


Fourth step: 

1st condition: break out the loop if the number is happy

Fifth step: 

2nd condition: break out the loop if the number is not happy

"When the number can't reach 1, it is not a happy number". This condition is really ambiguous, we have to do something more to it.

Well, let's think of this way:
Let's count from 0 - 9, ladies and gentlemen: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Notice that we can't split those numbers further.
So, it's safe to say that if the number reaches those digit (except 1) then it is not a happy number. 😓

Thus, we add this statement:


Last step: Finally, if we can still continue, we can utilize our own functions to repeat all the process again (aka recursive function)


But this is not the end, you can modify this to work with base 2 (or any base you love), or you can practice turning recursive function to while loop. I'll leave it to you then. 😋


Bye :D







Comments