4 ms·
This is a way prettyprint could have been written without branching: def prettyprint(a, b): fmt_string = {True:'%d is less than %d',False:'%d is hi
by bjourne 14y ago
This is a way prettyprint could have been written without branching:
def prettyprint(a, b):
fmt_string = {True:'%d is less than %d',False:'%d is higher than %d'}[a < b]
return fmt_string % (a, b)
Or even (and this is cheating by using the int constructor):
def prettyprint(a, b):
fmt_string = '%d ' + ['is higher than', 'is less than'][int(a < b)] ' %d'
return fmt_string % (a, b)
I think a good way to get acquainted with FP is to replace conditionals with lookup tables and lambda functions. But it is easy to overdo it, sometimes plain old if-statements are the most readable alternative.
- kzrdude 14y agoTrue and False are 1 and 0 in Python too, so no int constructor needed. (Try 3 + True == 4)
- slurgfest 14y agoTrue and False are not 1 and 0 in Python. >>> (1 is True) or (True is 1) False >>> (0 is False) or (False is 0) False >>> isinstance(0, bool) or isinstance(1, bool) False >>> isinstance(False, bool) and isinstance(True, bool) True Indexing with boolean expressions is bad style to begin with, but if you are going to do it then a bool cast shows explicitly what you are trying to do.
- peter-fogg 14y agoYou'll find that they are integers, though: >>> isinstance(True, int) True >>> bool.__mro__ (<type 'bool'>, <type 'int'>, <type 'object'>) Although they aren't literally the same object, 1 == True does evaluate to True.
- slurgfest 14y agoDownvoting notwithstanding, the statement that 1 and 0 ARE True and False is flat false. It's not even kind of true: True is not 1 and False is not 0, the type of True and False is not int, and the established convention for comparing to these values is to use 'is' if you are not using the vaguer 'if cond' or 'if not cond'.
- kzrdude 14y agoYou are missing the point. The original code was making detours instead of using True as the list index (which you can do).