...

/

A List Of Functions

A List Of Functions

We'll cover the following...

Now you’re going to add a level of abstraction. You started by defining a list of rules: if this, do that, otherwise go to the next rule. Let’s temporarily complicate part of the program so you can simplify another part.

Press + to interact
import re
def match_sxz(noun):
return re.search('[sxz]$', noun)
def apply_sxz(noun):
return re.sub('$', 'es', noun)
def match_h(noun):
return re.search('[^aeioudgkprt]h$', noun)
def apply_h(noun):
return re.sub('$', 'es', noun)
def match_y(noun): #①
return re.search('[^aeiou]y$', noun)
def apply_y(noun): #②
return re.sub('y$', 'ies', noun)
def match_default(noun):
return True
def apply_default(noun):
return noun + 's'
rules = ((match_sxz, apply_sxz), #③
(match_h, apply_h),
(match_y, apply_y),
(match_default, apply_default)
)
def plural(noun):
for matches_rule, apply_rule in rules: #④
if matches_rule(noun):
return apply_rule(noun)

① Now, each match rule is its own function which returns the results of calling the re.search() function.

② Each apply rule is also its own function which calls the re.sub() function to apply the appropriate pluralization rule.

③ Instead of having one function (plural()) with multiple rules, you have the rules data structure, which is a sequence of pairs of functions.

④ Since the rules have been ...