Created
December 25, 2023 13:23
-
-
Save VojtaStruhar/2dbef5bf18990da9aba0656ab13a6215 to your computer and use it in GitHub Desktop.
Benchmark of string and numerical approaches to the Happy Number Leetcode task.
This file contains hidden or 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
import timeit | |
def isHappyStr(n: int) -> bool: | |
seen = set() | |
current = str(n) | |
while current not in seen: | |
seen.add(current) | |
sum = 0 | |
for digit in current: | |
digit = int(digit) | |
sum += digit ** 2 | |
if sum == 1: | |
return True | |
current = str(sum) | |
return False | |
def isHappyNum(n: int) -> bool: | |
seen = set() | |
while n not in seen: | |
seen.add(n) | |
sum = 0 | |
while n > 0: | |
digit = n % 10 | |
sum += digit * digit | |
n //= 10 | |
if sum == 1: | |
return True | |
return False | |
inputs = [1, 11, 15, 25, 42, 69, 100, 128, 256, 123456789] | |
iterations = 500_000 | |
print(f"Benchmarking {len(inputs)} inputs with {iterations} iterations:\n") | |
print("isHappyNum:\t", timeit.timeit("[isHappyNum(n) for n in inputs]", globals=locals(), number=iterations)) | |
print("isHappyStr:\t", timeit.timeit("[isHappyStr(n) for n in inputs]", globals=locals(), number=iterations)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment