User:Fako Berkers/Markovchain: Difference between revisions

From XPUB & Lens-Based wiki
(Created page with "<source lang="python"> text = "He saw the cat before he saw the potato." dic = {} prevword = '' # Read the text into memory. for word in text.split(): if prevword != '': # doe...")
 
No edit summary
Line 17: Line 17:
print dic
print dic


# Pop the words in memory in their original order.
# Pop the words in memory to get their original order.
def readnorm(word):
def readnorm(word):

Revision as of 18:16, 26 April 2011

text = "He saw the cat before he saw the potato."
dic = {}
prevword = ''

# Read the text into memory.
for word in text.split():

	if prevword != '': # doesn't occur the first time
		dic[prevword].append(word) # write current word under previous word in dic

	if word not in dic: 
		dic[word] = [] # create word in dic
	
	prevword = word # remember previous word to write next word under current word

print dic

# Pop the words in memory to get their original order.
def readnorm(word):
	
	print word,
	
	if not dic[word]: # Reach the end of the sequence
		return True
	else:
		readnorm(dic[word].pop(0))

# Start random generator
import random
random.seed()

# Print words in a random order (but do not pop())
def readrand(word):
	
	print word,
	
	if not dic[word]: # Reach the end of the sequence
		return True
	else:
		ind = random.randrange(len(dic[word]))
		readrand(dic[word][ind])	

readrand("He")
print
readnorm("He")