Chapter 26
Functional Programming
While primarily thought of and designed as a scripting language, Python
supports several different programming paradigms. This chapter provides an
introduction to functional programming by revisiting a problem from Part II.
Listing 26.1: Word Frequency (Functional Version)
1 # wordfreqfp.py
2
3 import string
4 import itertools
5
6 def removepunc(s):
7 return s.translate(s.maketrans("", "", string.punctuation))
8
9 def getwords(fname):
10 with open(fname) as f:
11 return removepunc(f.read().lower()).split()
12
13 def frequency(words):
14 return list(map(lambda xy: (xy[0], len(list(xy[1]))),
15 itertools.groupby(sorted(words))))
Get A Concise Introduction to Programming in Python now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.