Created
March 20, 2018 13:46
-
-
Save ceeblet/b15de3fcad4471e68ebe3bd878ce0afc to your computer and use it in GitHub Desktop.
dicts as case or switch
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 dispatch_if(operator, x, y): | |
if operator == 'add': | |
return x + y | |
elif operator == 'sub': | |
return x - y | |
elif operator == 'mul': | |
return x * y | |
elif operator == 'div': | |
return x / y | |
else: | |
return None | |
def dispatch_dict(operator, x, y): | |
return { | |
'add': lambda: x + y, | |
'sub': lambda: x - y, | |
'mul': lambda: x * y, | |
'div': lambda: x / y, | |
}.get(operator, lambda: None)() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment