Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Check Whether a Number Is a "Happy Number"

Python Check Whether a Number Is a "Happy Number"

Document Object Reference Manual Python3 Examples

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

print

(

is_happy_number

(

19

)

)

 

Output True

print

(

is_happy_number

(

20

)

)

 

Output False

Code analysis:

  1. is_happy_number function is used to determine whether a number is a happy number.
  2. get_next function is used to calculate the sum of the squares of the digits of a number.
  3. seen set is used to record numbers that have already appeared, to prevent entering an infinite loop.
  4. in while loop, continuously calculate the next number until the result is 1 or a loop is entered.
  5. Finally, return n == 1, if the result is 1, return True; otherwise, returns False。

Output result:

True
False

Document Object Reference Manual Python3 Examples