Created
January 18, 2021 13:35
-
-
Save GoodClover/ca7c8318abc32ce2f006ba46be8eb7d0 to your computer and use it in GitHub Desktop.
Stupid question for flipping 4 and 7
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
"stoopid" | |
def f_ternary(x: int) -> int: | |
return 4 if x == 7 else 7 | |
def f_old_ternary(x: int) -> int: | |
return x == 4 and 7 or 4 | |
def f_dict(x: int) -> int: | |
return {4: 7, 7: 4}[x] | |
def f_dict_getitem(x: int) -> int: | |
return {4: 7, 7: 4}.__getitem__(x) | |
f_dict_no_overhead = {4: 7, 7: 4}.__getitem__ | |
def f_list(x: int) -> int: | |
return [0, 0, 0, 0, 7, 0, 0, 4][x] | |
def f_addition(x: int) -> int: | |
return 11 - x | |
def f_bitflip(x: int) -> int: | |
return x ^ 0b11 | |
def f_weird_lambda(x: int) -> int: | |
l = list(range(8)) | |
l[4] = lambda: 7 | |
l[7] = lambda: 4 | |
try: | |
return l[x]() | |
except (TypeError, IndexError): | |
raise ValueError("Number must be 4 or 7") | |
def f_no_lambda_but_dict(x: int) -> int: | |
try: | |
return {4: 7, 7: 4}[x] | |
except IndexError: | |
raise ValueError("Number must be 4 or 7") | |
## test | |
if __name__ == "__main__": | |
import timeit | |
FUNCS = [ | |
f_ternary, | |
f_old_ternary, | |
f_dict, | |
f_dict_getitem, | |
f_dict_no_overhead, | |
f_list, | |
f_addition, | |
f_bitflip, | |
f_GoodClover_weird_lambda, | |
f_GoodClover_fixed_no_lambda_but_dict, | |
] | |
NUMBER = 2 ** 12 | |
RESULT_SCALE = 100000 | |
print(f"Running each function {NUMBER} times for each test.") | |
print(f"Result num = round(timeit * {RESULT_SCALE})") | |
for f in FUNCS: | |
if f(4) == 7: | |
result = timeit.timeit(lambda: f(4), number=NUMBER) | |
print(f"\u001B[93m{f.__name__ : >48}\u001B[0m: (4) -> 7 ¦ \u001B[36m{round(result*RESULT_SCALE)!r:>5}\u001B[0m") | |
else: | |
print(f"\u001B[93m{f.__name__ : >48}\u001B[0m: (4) -> 7 ¦ \u001B[41m\u001B[97mAssertion Failure\u001B[0m") | |
if f(7) == 4: | |
result = timeit.timeit(lambda: f(7), number=NUMBER) | |
print(f"\u001B[93m{f.__name__ : >48}\u001B[0m: (7) -> 4 ¦ \u001B[36m{round(result*RESULT_SCALE)!r:>5}\u001B[0m") | |
else: | |
print(f"\u001B[93m{f.__name__ : >48}\u001B[0m: (7) -> 4 ¦ \u001B[41m\u001B[97mAssertion Failure\u001B[0m") | |
print() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment