In this paper, the method of realizing the algorithm of the Markov chain by Python is described. Share to everyone for your reference. The specific analysis is as follows:
In the "Programming Practice" (English name "The Practice of Programming") of the book, the third chapter of the C language, C++,awk and Perl respectively, the implementation of the MA-fu chain algorithm, to enter through the text, "random" to generate some useful text.
Description
1. The program uses a dictionary, a dictionary and a hash is not a thing, a dictionary is a set of key-value pairs, and a hash is a constant-order insertion, deletion, but a hash can be used to implement a dictionary.
2. The SetDefault () method of the dictionary makes the program much less conditional judgment.
3. Random.choice () can randomly remove elements from a sequence.
4. Each of the two prefix words determines a suffix.
Implementation code:
Import Randomimport Sysmaxgen = 10000NONWORD = ' \ n ' w1 = W2 = Nonwordstatetab = {}text = Sys.stdin.read () words = Text.split () for word in words: Statetab.setdefault ((W1, W2), []). Append (Word) w1, w2 = W2, word# add Tailstatetab.setdefault ((W1, W2), []). Append (Nonword) # show Mar wordsw1 = W2 = Nonwordfor i in Xrange (Maxgen): Suf = St atetab[(W1,W2)] t = random.choice (SUF) if t = = nonword:break print t w1, w2 = W2, T
Hopefully this article will help you with Python programming.