Unexpected output from "mimic" function exercise from Google Python Class
<p>First of all, apologies if some stupid error lies ahead: I have just started to ("re")learn Python (I am using Python 2.7).</p>

<p>I have completed one exercise from the Google Python Class, called "mimic", but I'm sometimes getting some strange results and I would like to understand why this is happening.</p>

<p>The exercise asks the following things:</p>

<p>1) Read in the file specified on the command line.</p>

<p>2) Build a "mimic" dict that maps each word that appears in the file to a list of all the words that immediately follow that word in the file. The list of words can be be in any order and should include duplicates. So for example the key "and" might have the list ["then", "best", "then", "after", ...] listing all the words which came after "and" in the text. We'll say that the empty string is what comes before the first word in the file.</p>

<p>3) With the mimic dict, it's fairly easy to emit random text that mimics the original. Print a word, then look up what words might come next and pick one at random as the next work. Use the empty string as the first word to prime things.
If we ever get stuck with a word that is not in the dict, go back to the empty string to keep things moving.</p>

<p>This is my code:</p>

<pre><code>import random
import sys

def mimic_dict(filename):
  """Returns mimic dict mapping each word to list of words which follow it."""
  d = {}
  with open(filename) as f:
    text = f.read()
    words = text.split()
  i = 0
  for i in range(len(words) - 1):
    if words[i] not in d:
      d[words[i]] = [words[i + 1]]
    else:
      d[words[i]].append(words[i+1])
    i += 1
  d[''] = words[0]
  return d

def print_mimic(d, word):
  """Given mimic dict and start word, prints 200 random words."""
  mimic_text = []
  while len(mimic_text) &lt; 200:
    if word in d:
      next_word = random.choice(d[word])
      mimic_text.append(next_word)
      word = next_word
    else:
      word = ''
  print ' '.join(mimic_text)

# Provided main(), calls mimic_dict() and mimic()
def main():
  if len(sys.argv) != 2:
    print 'usage: ./mimic.py file-to-read'
    sys.exit(1)

  dict = mimic_dict(sys.argv[1])
  print_mimic(dict, '')

if __name__ == '__main__':
  main()
</code></pre>

<p>Now, the problem is that if I feed this mimic function with a very simple text file, <a href="https://www.dropbox.com/s/kanodc7q74kj05i/small.txt?dl=0" rel="nofollow">small.txt</a>, which contains this:</p>

<pre><code>We are not what we should be
We are not what we need to be
But at least we are not what we used to be
  -- Football Coach
</code></pre>

<p>the output looks like this:</p>

<pre><code>e W e W W W W W e e e e e W e W [...]
</code></pre>

<p>That is, a random sequence of the letters of the first word.</p>

<p>But, if I run it on a much longer file (<a href="https://www.dropbox.com/s/hwajarrejovpz77/alice.txt?dl=0" rel="nofollow">alice.txt</a>, that contains the whole text from Alice in Wonderland), I get some random letters at the beginning (and sometimes not even those letters), but then somehow it works, here are some examples:</p>

<p>Run 1 output (truncated):</p>

<pre><code>l i ' s l e ' ' i ' e s e c s ' A large flower-pot that the next[...]
</code></pre>

<p>Run 2 output (truncated):</p>

<pre><code>i i i A little door, staring at all,' said in fact, [...]
</code></pre>

<p>Run 3 output (truncated):</p>

<pre><code> A Caucus-Race and she found out of Hearts,[...]
</code></pre>

<p>It seems that once it gets to the letter "A" it starts working as expected, but I really can't understand what's going on before getting to that letter.
I am sure there is just a stupid bug somewhere, but I can't find it, and I would be really thankful if some gentle soul could take some time to help me understand what's going on here.</p>

<p>Thank you very much!</p>

<p>You missed two characters.</p>

<p><code>d[''] = words[0]</code> should be <code>d[''] = [words[0]]</code>.</p>

python python-2.7