72. Happy number
Take a whole number, replace it by the sum of the squares of its digits, and repeat. For 19: 1² + 9² = 82, then 8² + 2² = 68, then 6² + 8² = 100, then 1² + 0² + 0² = 1. A number that reaches 1 this way is called happy.
Other numbers never reach 1: they fall into a loop that goes round forever. 2 goes 4, 16, 37, 58, 89, 145, 42, 20, and back to 4.
Write a function is_happy(n) that takes a whole number n and returns True if it is happy, or False if it ends
up in a loop. 1 itself is happy. Your function must stop either way, so it needs a way to notice a loop.
Example 1
n = 19TrueExample 2
n = 2FalseExample 3
n = 1TrueConstraints
nis a whole number from 1 to 10^9.
Submit also runs 9 more tests you can't see.
Practises Sets (lesson 12).
- Write a helper for one step: take the digits off with
n % 10andn // 10(or go throughstr(n)), adding up their squares. - A loop means a number comes back. Keep a set of every number seen; if the next number is already in it, the steps will repeat forever.
- Loop
while n != 1 and n not in seen, addingnto the set before each step. A fixed number of steps can't tell a slow happy number (78999 takes 7) from a loop.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
def is_happy(n):
"""Check whether n is a happy number.
n: int, 1 or more
Returns: bool, True if the digit-square sums reach 1,
False if they loop forever
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.