Python Determine if a Number is a "Happy Number"

Document 对象参考手册Python3 Examples

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

Code explanation:

  1. is_happy_numberThis function is used to determine whether a number is a happy number.
  2. get_nextThis function is used to calculate the sum of squares of each digit of a number.
  3. seenThe set is used to record numbers that have already appeared, to prevent entering an infinite loop.
  4. InwhileIn the loop, keep calculating the next number until the result is 1 or it enters a cycle.
  5. Finally returnn == 1, return True if the result is 1True, otherwise returnFalse。

Output result:

True
False

Document 对象参考手册Python3 Examples

Other extensions