Last active
December 26, 2015 19:19
-
-
Save gatesphere/7201086 to your computer and use it in GitHub Desktop.
Passing comparison operators in Python
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
## approach 1 | |
def myfun(a, b, mode='<'): | |
valid_modes = ['<', '<=', '>', '>=', '==', '!='] | |
if mode not in valid_modes: | |
print 'Error!' | |
... # error handling code here | |
return | |
if mode == '<': | |
if a < b: | |
... | |
elif mode == '<=': | |
if a <= b: | |
... | |
elif mode == '>': | |
if a > b: | |
... | |
elif mode == '>=': | |
if a >= b: | |
... | |
elif mode == '==': | |
if a == b: | |
... | |
elif mode == '!=': | |
if a != b: | |
... | |
else: | |
print 'Something went horribly wrong. Blame cosmic rays.' |
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
## approach 2 | |
# comparators | |
cmp_lt = lambda x,y: x < y | |
cmp_gt = lambda x,y: x > y | |
cmp_eq = lambda x,y: x == y | |
cmp_lte = lambda x,y: x <= y | |
cmp_gte = lambda x,y: x >= y | |
cmp_neq = lambda x,y: x != y | |
def myfun(a, b, comparator): | |
if comparator(a,b): | |
... | |
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
## python is batteries included! | |
import operator | |
def myfun(a, b, comparator): | |
if comparator(a,b): | |
... |
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
## don't do this, dummy | |
def myfun(a, b, mode='<'): | |
if eval(str(a)+mode+str(b)): | |
... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment