10 Telephone: Randomly mutating strings

 

“What we have here is a failure to communicate.”

--Captain

Now that we’ve played with randomness, let’s apply the idea to randomly mutating a string. This is interesting, because strings are actually immutable in Python. We’ll have to figure out a way around that.

To explore these ideas, we’ll write a version of the game of Telephone where a secret message is whispered through a line or circle of people. Each time the message is transmitted, it’s usually changed in some unpredictable way. The last person to receive the message will say it out loud to compare it to the original message. Often the results are nonsensical and possibly comical.


We will write a program called telephone.py that will mimic this game. It will print “You said: ” and the original text, followed by “I heard: ” with a modified version of the message. As in chapter 5, the input text may come from the command line:

$ ./telephone.py 'The quick brown fox jumps over the lazy dog.'
You said: "The quick brown fox jumps over the lazy dog."
I heard : "TheMquick brown fox jumps ovMr t:e lamy dog."

Or it may come from a file:

$ ./telephone.py ../inputs/fox.txt
You said: "The quick brown fox jumps over the lazy dog."
I heard : "The quick]b'own fox jumps ovek the la[y dog."

10.1 Writing telephone.py

10.1.1 Calculating the number of mutations

10.1.2 The mutation space

10.1.3 Selecting the characters to mutate

10.1.4 Mutating a string

10.1.5 Time to write

10.2 Solution

10.3 Discussion

10.3.1 Mutating a string

10.3.2 Using a list instead of a str

10.4 Going further

Summary