An example analysis of the algorithm of the Markov chain in Python

Source: Internet
Author: User
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.

  • Related Article

    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.