User:Dusan Barok/Markov Chain: Difference between revisions

From XPUB & Lens-Based wiki
(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(): ...")
 
No edit summary
 
Line 1: Line 1:
<code>
<source lang="python">
import random
import random
from pprint import pprint
from pprint import pprint
Line 23: Line 23:
         break
         break


</code>
</source>

Latest revision as of 21:17, 27 May 2011

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