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))))
16
17 def main():
18 print(frequency(getwords("moby.txt")))
19
20 main() ...

Get A Concise Introduction to Programming in Python now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.