Exercise 47 of learn python the hard book