Python program that uses a for loop and the is_happy()
function to print all happy numbers between 1 and 100:
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
for i in range(1,101):
if is_happy(i):
print(i)
This program uses a for loop to iterate over the range 1 to 100, and for each number, it checks if it is a happy number by calling the is_happy(n)
function. If the function returns True
, it prints the number.
The function is_happy(n)
is defined earlier as a helper function that 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
.
This program will print all the happy numbers between 1 to 100, which are 1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 68, 70, 79, 82, 86, 91, 94, 97.