Last active
March 23, 2022 02:01
-
-
Save wimglenn/d6c0ffb06e0e40e247cd6eacb0d54745 to your computer and use it in GitHub Desktop.
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 random | |
import re | |
import timeit | |
import matplotlib.pyplot as plt | |
from collections import Counter | |
def sum_digits_math(n): | |
"""from https://stackoverflow.com/a/14940026/674039""" | |
r = 0 | |
while n: | |
r, n = r + n % 10, n // 10 | |
return r | |
def sum_digits_str_dumb(n): | |
"""from OP https://stackoverflow.com/q/14939953/674039""" | |
return sum(int(i) for i in str(n)) | |
def sum_digits_re(n): | |
"""from https://stackoverflow.com/a/71576042/674039""" | |
d = str(n) | |
return sum(int(s) * re.subn(s, "", d)[1] for s in "123456789") | |
def sum_digits_str_fast(n): | |
d = str(n) | |
return sum(int(s) * d.count(s) for s in "123456789") | |
def sum_digits_counter(n): | |
c = Counter(str(n)) | |
return sum(int(k) * v for k, v in c.items()) | |
funcs = [f for name, f in locals().items() if name.startswith("sum_digits_")] | |
results = {f: [] for f in funcs} | |
for n_digits in range(1, 200): | |
digits = random.choices("0123456789", k=n_digits) | |
n = int("".join(digits)) | |
assert len({f(n) for f in funcs}) == 1 | |
for func in funcs: | |
t = timeit.timeit(lambda: func(n), number=10) | |
results[func].append(t) | |
for func in funcs: | |
plt.plot(results[func], label=func.__name__) | |
plt.xlabel("len(str(n))") | |
plt.ylabel("t") | |
plt.legend() | |
plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment