Skip to content

Instantly share code, notes, and snippets.

@funilrys
Last active April 8, 2018 09:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save funilrys/6a7a7244006069bbac6bec1458db1641 to your computer and use it in GitHub Desktop.
Save funilrys/6a7a7244006069bbac6bec1458db1641 to your computer and use it in GitHub Desktop.
This module helps to find out if a number is happy or unhappy. More notes about each function at: https://funilrys.com/programming/python/happy-numbers
#!/usr/bin/env python3
"""
This module helps to find out if a number is happy or unhappy.
"""
def given_number():
"""
This function ask the user for a number and return it so it can be
usable by other functions.
Returns: int
The given number.
"""
while True:
try:
initial_number = abs(int(input("Give us a number ")))
break
except ValueError:
continue
return initial_number
def split_digits(digits):
"""
This function split each digits of a given number.
Argument:
- digits: int
The number to split.
Returns: list
A list with each digit.
"""
return map(int, str(digits))
def calculation(digits):
"""
This function return the calculation of the sum of the square of each digits.
Returns: int
The result of the recursively sum of squares of each digits.
"""
result = 0
for digit in digits:
result += pow(digit, 2)
return result
def is_happy(number, return_sequence=False):
"""
This function check if a number is happy or not.
Argument:
- number: int
The number to check.
- return_sequence: bool
If True we return the sequence of results.
Returns: bool or tuple
- True: number is happy.
- False: number is unhappy.
- tuple: if return_sequence == True
- We return (True|False, past_results)
"""
past_results = []
list_of_digits = split_digits(number)
while True:
current_result = calculation(list_of_digits)
if current_result not in past_results:
if current_result != 1:
list_of_digits = split_digits(current_result)
past_results.append(current_result)
elif return_sequence:
return (True, past_results)
return True
elif return_sequence:
return (False, past_results)
return False
if __name__ == '__main__':
NUMBER = given_number()
if is_happy(NUMBER):
print('%d is a happy number' % NUMBER)
else:
print('%d is an unhappy number' % NUMBER)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment