User:Dusan Barok/Markov Chain

From XPUB & Lens-Based wiki
< User:Dusan Barok
Revision as of 22:09, 27 May 2011 by Dusan (talk | contribs) (Created page with "<code> import random from pprint import pprint text = "he saw the black cat before she saw the red potato he hated ." dictionary = {} lastword = "" for word in text.split(): ...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

import random from pprint import pprint

text = "he saw the black cat before she saw the red potato he hated ." dictionary = {} lastword = ""

for word in text.split():

   if lastword:
       if lastword not in dictionary:
           dictionary[lastword]=[]
       dictionary[lastword].append(word)
   lastword = word

pprint(dictionary)

word = "he" while True:

   print word
   word = random.choice(dictionary[word])
   if word not in dictionary:
       break