Use python to analyze the Markov Chain Algorithm Instances and use python to analyze instances.
This article describes how to implement the Markov Chain Algorithm in python. Share it with you for your reference. The specific analysis is as follows:
In The program design Practice (The Practice of Programming), Chapter 3 uses C language, C ++, AWK, and Perl to implement The Markov Chain Algorithm, to generate some useful text randomly based on the input text.
Note:
1. the program uses a dictionary. The dictionary and hash are not a set of key-value pairs, while the hash is a constant-order insertion and deletion function, however, you can use hash to implement the dictionary.
2. The setdefault () method of the Dictionary makes the program less conditional judgment.
3. random. choice () can randomly retrieve elements in a sequence.
4. Determine a suffix for each two prefix words.
Implementation Code:
Import randomimport sysMAXGEN = 10000 NONWORD = '\ 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 = statetab [(w1, w2)] t = random. choice (suf) if t = NONWORD: break print t w1, w2 = w2, t
I hope this article will help you with Python programming.