Created
September 11, 2022 11:05
-
-
Save codecakes/865ac123abf54e450b7173253649207b to your computer and use it in GitHub Desktop.
A number is happy if recursively all the sums of squares of inidividual digits equal 1 otherwise its false if numbers keep repeating.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def happy_number(x: int, result=0, seen: Optional[set] = None) -> bool: | |
seen = seen or set() | |
num_to_sqr, new_num = ((x%10)**2 + result), x//10 | |
# print(f"1st num_to_sqr={num_to_sqr} new_num={new_num}") | |
seen.add(num_to_sqr) | |
# print(f"seen={seen}") | |
if new_num: | |
res = happy_number(new_num, num_to_sqr, seen) | |
# print(f"res={res}") | |
return res | |
if num_to_sqr in seen: | |
return False | |
if num_to_sqr == 1: | |
return True | |
else: | |
return happy_number(num_to_sqr, 0, seen) | |
# print(f"num_to_sqr={num_to_sqr}") | |
return False | |
print(happy_number(200)) | |
print(happy_number(19)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment