title: python code explanation
body: <p>I have been studying this code to generate random text:</p>
  
  <pre><code>from collections import defaultdict, Counter
  from itertools import ifilter
  from random import choice, randrange
  
  def pairwise(iterable):
      it = iter(iterable)
      last = next(it)
      for curr in it:
          yield last, curr
          last = curr
  
  valid = set('abcdefghijklmnopqrstuvwxyz ')
  
  def valid_pair((last, curr)):
      return last in valid and curr in valid
  
  def make_markov(text):
      markov = defaultdict(Counter)
      lowercased = (c.lower() for c in text)
      for p, q in ifilter(valid_pair, pairwise(lowercased)):
          markov[p][q] += 1
      return markov
  
  def genrandom(model, n):
      curr = choice(list(model))
      for i in xrange(n):
          yield curr
          if curr not in model:   # handle case where there is no known successor
              curr = choice(list(model))
          d = model[curr]
          target = randrange(sum(d.values()))
          cumulative = 0
          for curr, cnt in d.items():
              cumulative += cnt
              if cumulative &gt; target:
                  break
  
  model = make_markov('The qui_.ck brown fox')
  print ''.join(genrandom(model, 20))
  </code></pre>
  
  <p>However i am having trouble understanding the last bit, from target = randrange(sum(d.values())) onwards.
  An explanation would be greatly appreciated! Thanks!</p>