Fortune

April 5, 2011

We have today another in our occasional series of re-implementations of Unix V7 commands. The fortune command prints a random aphorism on the user’s terminal; many people put the fortune command in their login script so they get a new aphorism every time they login. Here’s the man page:

NAME

fortune

SYNOPSIS

fortune [ file ]

DESCRIPTION

Fortune prints a one-line aphorism chosen at random. If a file is specified, the sayings are taken from that file; otherwise they are selected from /usr/games/lib/fortunes.

Your task is to implement the Unix V7 fortune program. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

Nice one Mike; I need to learn more about the itertools module.
Quick question, though: randint(0, n) uniformly picks a random integer from [0, n]
(inclusive), so doesn’t this use the probability 1/(n + 1) instead of 1/n?

@Graham. Yes, my program calculates the probability as 1/(n+1). However, n starts at 0.
So, for fortune lines 0, 1, 2, …, the probabilities are 1/1, 1/2, 1/3, ….
This is the same as n starting at 1 and calculating the probability as 1/n.