Python Determine if a Number is a "Happy Number"
A happy number is a number where you add the squares of each digit to get a new number, and repeat this process until the final result is 1, or it enters a cycle that does not contain 1. If the final result is 1, then the number is a happy number.
Example
def is_happy_number(n):
def get_next(number):
return sum(int(char) ** 2 for char in str(number))
seen = set()
while n != 1 and n not in seen:
seen.add(n)
n = get_next(n)
return n == 1
# Test
print(is_happy_number(19)) # Output True
print(is_happy_number(20)) # Output False
def get_next(number):
return sum(int(char) ** 2 for char in str(number))
seen = set()
while n != 1 and n not in seen:
seen.add(n)
n = get_next(n)
return n == 1
# Test
print(is_happy_number(19)) # Output True
print(is_happy_number(20)) # Output False
Code explanation:
is_happy_numberThis function is used to determine whether a number is a happy number.get_nextThis function is used to calculate the sum of squares of each digit of a number.seenThe set is used to record numbers that have already appeared, to prevent entering an infinite loop.- In
whileIn the loop, keep calculating the next number until the result is 1 or it enters a cycle. - Finally return
n == 1, return True if the result is 1True, otherwise returnFalse。
Output result:
True FalseOther extensions
Python3 Examples