The quickest, and easiest to explain would be:
score_to_range = {
0: ‘low’,
1: ‘moderate’,
2: ‘high’
}
score_to_range[int((score - 39) / 69.0)]
or something like that.
To dispatch functions on the type of their first argument (singular dispatch), I’ve been using the following.
from collections import OrderedDict
class pattern(OrderedDict):
def __call__(self, *args, **kwargs):
return self[type(args[0])](*args, **kwargs)
more = pattern({
int: lambda x: x + 1,
str: lambda x: x + 's'
})
more(1) == 2
more('noun') == 'nouns'
more[int](1) == 2
# more[int]('noun') raises TypeError
I find this a little more flexible than
http://www.python.org/dev/peps/pep-0443/
These could be merged into the following to simplify:
class score_to_range_builder(dict):
def __call__(self, score):
return self[int((score - 39) / 69.0)]
score_to_range = score_to_range_builder().update({
0: ‘low’,
1: ‘moderate’,
2: ‘high’
})
score_to_range(52) == ‘moderate’
Inheriting from OrderedDict isn’t necessary in this case, but it is useful for the pattern class because if we put basestring and str in as keys, the order would matter.
I’ll work on a blog post about this soon.
--
Kyle Marek-Spartz