程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[original launch] learn Python enumeration algorithm from Xiao Hui

編輯:Python

This article has participated in 「 New people's creation ceremony 」 Activities , Start the road of nuggets creation together .

 Statement : The copyright belongs to me , Offenders will investigate .
Please quote source for reprint https://juejin.cn/post/7111941657045499912

1.1.  Enumeration algorithm

1.1.1.  Algorithm definition

In inductive reasoning , If you examine all possible situations of a certain type of event one by one , Therefore, a general conclusion is drawn , Then the conclusion is reliable , This method of induction is called enumeration .

1.1.2.  The basic idea

The basic idea of enumeration algorithm is , List all the possible answers to the question , Judge one by one according to the conditions , Choose the answer that meets your needs . The design steps are :

(1) Select the appropriate range of research objects .

(2) Find the condition to judge the correct solution .

(3) Examine all subjects in the scope one by one

The execution process is as follows :  

The idea of this algorithm is simple , Easy to understand , The correctness of the algorithm is easy to prove ; But when the enumeration range is large , According to different conditions , It will be inefficient in some cases .

1.1.3.  Algorithm example -- A hundred dollars for a hundred chickens

Problem description :

Each cock 5 element , Each hen 3 element , Three chicks 1 element , use 100 Yuan to buy 100 chicken , Ask the rooster 、 hen 、 How many chickens each ?

Algorithm analysis :

The enumeration method is used to solve this problem , Take the number of three kinds of chickens as the enumeration object , Set as mj、gj and xj, Use the total number of three kinds of chickens (mj+gj+xj=100) And the total amount of money for chicken (gj5+mj3+xj/3==100) As a judgment condition , List the number of chickens . Among them, the rooster 5 element / only , You can buy at most 20 A rooster ; hen 3 element / only , You can buy at most 33 A hen ; Chick 1 element / only , You can buy at most 100 only .

Code implementation :

【 example 1-1】  A hundred dollars for a hundred chickens :

for gj in range(0,23):\
    for mj in range(0,34):\
        xj = 100-gj-mj\
        if xj%3==0 and gj*5+mj*3+xj/3==100:\
            print("100 Yuan can buy a rooster :{}, hen :{}, Chick :{}".format(gj, mj, xj))

Execution results :

100 Yuan can buy a rooster :0, hen :25, Chick :75
100 Yuan can buy a rooster :4, hen :18, Chick :78
100 Yuan can buy a rooster :8, hen :11, Chick :81
100 Yuan can buy a rooster :12, hen :4, Chick :84

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved