Use python to analyze the Markov chain algorithm examples

Source: Internet
Author: User
This article mainly introduces how to implement the Markov chain algorithm in python. The example analyzes the principles and implementation skills of the Markov chain algorithm, for more information, see the example in this article. 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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.