O'Reilly logo

A Concise Introduction to Programming in Python by Mark J. Johnson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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() ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required