Python implementation of BDA3 Chapter 21.2