Python Check Whether a Number Is a "Happy Number"
A happy number is a number that, when you square each digit and sum them to get a new number, and repeat this process until the final result is 1 or it enters a loop that does not contain 1. If the final result is 1, 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
Testing
(
is_happy_number
(
19
)
)
Output True
(
is_happy_number
(
20
)
)
Output False
Code analysis:
is_happy_numberfunction is used to determine whether a number is a happy number.get_nextfunction is used to calculate the sum of the squares of the digits of a number.seenset is used to record numbers that have already appeared, to prevent entering an infinite loop.- in
whileloop, continuously calculate the next number until the result is 1 or a loop is entered. - Finally, return
n == 1, if the result is 1, returnTrue; otherwise, returnsFalse。
Output result:
True
False
Python3 Examples