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