|
|
|
|
|
by bjourne
4875 days 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. |
|