An example analysis of the horse-ear-chain algorithm implemented by Python

Source: Internet
Author: User

In this paper, the method of implementing the Markov chain algorithm in Python is described. Share to everyone for your reference. The specific analysis is as follows:

In the book "The Practice of Programming" (English name "The Practice of Programming"), the third chapter, respectively, uses the C language, C++,awk and Perl respectively to implement the horse-ear-chain algorithm to generate some useful text through the input of the text, "random".

Description

1. The program uses a dictionary, dictionary and Hash is not a thing, the dictionary is a set of key-value pairs, and hashing is a constant order to insert, delete, but you can use hash to implement the dictionary.

2. The SetDefault () method of the dictionary makes the procedure 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:

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21-22 Import random Import sys Maxgen = 10000 Nonword = ' n ' w1 = W2 = Nonword Statetab = {} text = Sys.stdin.read () words = text . Split () for Word in Words:statetab.setdefault (W1, W2), []). Append (Word) w1, W2 = W2, Word # Add tail statetab.setdefault ((W1, W2), []). Append (Nonword) # show Mar words w1 = W2 = Nonword to I in Xrange (maxgen): Suf = statetab[(w1,w2)] t = Rand Om.choice (SUF) If t = = nonword:break print t w1, w2 = W2, T

I hope this article will help you with your 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.