Skip to content

Instantly share code, notes, and snippets.

@relsqui
Created November 29, 2017 06:48
Show Gist options
  • Save relsqui/9157c1750e47c611c9e563cb7a4951ba to your computer and use it in GitHub Desktop.
Save relsqui/9157c1750e47c611c9e563cb7a4951ba to your computer and use it in GitHub Desktop.
Automating "if x < a, elif x < b, elif x < c ..." blocks.
degrees = {0: "no", 2:"a little", 5:"some", 8:"quite a bit of", 11:"way too much"}
def degree(d):
for threshold, descriptor in sorted(degrees.items(), key=lambda x: x[0]):
if d <= threshold:
return descriptor
return degrees[max(degrees.keys())]
for x in range(15):
print("{0}\tI ate {1} candy.".format(x, degree(x)))
"""
0 I ate no candy.
1 I ate a little candy.
2 I ate a little candy.
3 I ate some candy.
4 I ate some candy.
5 I ate some candy.
6 I ate quite a bit of candy.
7 I ate quite a bit of candy.
8 I ate quite a bit of candy.
9 I ate way too much candy.
10 I ate way too much candy.
11 I ate way too much candy.
12 I ate way too much candy.
13 I ate way too much candy.
14 I ate way too much candy.
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment