A happy number is a number that eventually reaches 1 when replaced by the sum of the squares of its digits in a process called digit-square-sum. For example, the number 7 is a happy number because 7 -> 49 -> 97 -> 130 -> 10 -> 1.
Here is a Python program that uses a while loop and the split()
method to check if a given number is a happy number:
def is_happy(n):
seen = set()
while n not in seen:
seen.add(n)
n = sum(int(i)**2 for i in str(n))
return n == 1
# Example usage
num = 7
print(is_happy(num))
The function is_happy(n)
takes an integer as an argument, it uses a while loop to iterate until the number is in a set called seen. It uses the str(n)
method to convert the number to a string, and then the split()
method to split the string into a list of digits. It uses a list comprehension to square each digit and sum the squares up. The result is the new value of n. The while loop continues until n is in the set seen, which means it has been seen before and it’s in a loop that doesn’t lead to 1. In that case, the function returns False
, otherwise, it returns True
The example usage calls the is_happy()
function passing the number 7 as an argument, which returns True because 7 -> 49 -> 97 -> 130 -> 10 -> 1.
You could also use a set to keep track of the numbers that were seen during the process. If the current number is already in the set, it means that the number is in a loop that doesn’t lead to 1 and the function should return False.
def is_happy(n):
seen = set()
while n != 1:
if n in seen:
return False
seen.add(n)
n = sum(int(i) ** 2 for i in str(n))
return True
This method uses a set to keep track of the numbers that were seen during the process. If the current number is already in the set, it means that the number is in a loop that doesn’t lead to 1 and the function should return False. Otherwise, the function return True.