Last active
March 8, 2020 13:49
-
-
Save pedrominicz/8856765526a553c4b36a5e6968b21caa to your computer and use it in GitHub Desktop.
Type-checking decorator and bogosort.
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
#!/usr/bin/env python3 | |
import random | |
import types | |
def typecheck(f: types.FunctionType) -> types.FunctionType: | |
s = lambda x: repr(repr(x)) | |
def wrapper(*args, **kwargs): | |
keys = list(f.__annotations__.keys()) | |
get = f.__annotations__.get | |
for i, arg in enumerate(args): | |
type = get(keys[i]) | |
if not isinstance(arg, type): | |
raise TypeError(f'{s(arg)} is not an instance of {s(type)}') | |
for key, arg in kwargs.items(): | |
type = get(key) | |
if not isinstance(arg, type): | |
raise TypeError(f'{s(arg)} is not an instance of {s(type)}') | |
result = f(*args, **kwargs) | |
type = get('return') | |
if not isinstance(result, type): | |
raise TypeError(f'return type is not an instance of {s(type)}') | |
return result | |
return wrapper | |
@typecheck | |
def is_sorted(x: list) -> bool: | |
for i in range(len(x) - 1): | |
if x[i] > x[i + 1]: | |
return False | |
return True | |
@typecheck | |
def bogosort(x: list) -> list: | |
while not is_sorted(x): | |
random.shuffle(x) | |
return x | |
x = [1, 2, 3, 4, 5] | |
random.shuffle(x) | |
print(bogosort(x)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment