Commonly used algorithm - enumeration algorithm

    When conducting inductive reasoning, if all possible situations of a certain type of events are examined one by one, and a general conclusion is drawn, then this conclusion is reliable. This inductive method is called enumeration algorithm.

1. Basic concepts and algorithms

    The enumeration algorithm is referred to as the enumeration method, also known as the enumeration method and the brute force method. It is a concrete embodiment of the brute force strategy, also known as the brute force method.

    The basic idea of ​​the enumeration method is: enumerate all the situations involved in the problem one by one, and test which ones are the solutions to the problem and which ones should be excluded according to the conditions raised by the problem.

  • The meaning of the enumeration

1) Can make full use of the speed of the computer to solve some common problems

2) If the scale of the problem is not large, using enumeration, the calculation speed is acceptable.

3) Enumeration can be used as the bottom line of the time performance of certain types of problems, which can be used to elicit more efficient algorithms for the same problem.

  • Enumeration implementation steps (algorithms)

1) Determine the enumeration amount (simple variable or array) according to the specific situation of the problem

2) Determine the enumeration range according to the specific emptying of the problem, and set the enumeration cycle

3) Determine the screening (constraint) conditions according to the specific requirements of the problem

4) Design the enumeration program, run and debug it, analyze and discuss the running results.

2. Judging the Armstrong number

Example 1 Find the " Armstrong number "     with three to ten digits .

    The so-called " Armstrong number " refers to a number with three or more digits, and the sum of the powers of the digits of each digit is equal to itself. Example: 153 is an Armstrong number because

    153=1^{3}+5^{3}+3^{3}

    472335975 is an Armstrong number because

    472335975=4^{9}+7^{9}+2^{9}+3^{9}+3^{9}+5^{9}+9^{9}+7^{9}+5^{9}

Among them, Armstrong numbers     with different digits also have aliases, such as the Armstrong number with three digits is also called " Narcissus number ", and the Armstrong number with seven digits is also called " Big Dipper number " and so on.

    Then the value range of this question is 100-10000000000 ( 10^{10}, not included), and the condition is limited to the sum of the powers of the digits of each number equal to itself.

    How to get the digits ?

Divisibility and remainder     can be used to obtain digits, but the number of digits is not fixed and it is not easy to handle, so it can be converted into a string, find the length (number of powers), and take the string element (each digit).

    The syntax for converting a value to a string is:

str ( numeric expression )

    After conversion, the positive number does not contain a sign bit, the string is a sequence, and each character is an element.

    f format string: f-string uses {content:format} to set the string format, where content is the content to replace and fill in the string, which can be a variable, expression or function, etc., and format is a format descriptor. It is not necessary to specify ":format" to use the default format. Its syntax format is:

f'{ string / variable : format }'

Among them: before and after curly braces: any string can be placed, and they will be directly displayed in the result; inside curly braces: target string + target format; before the colon: the original string or variable that needs to be formatted, after the colon: required The target format (the default format is used by default)

The complete procedure is as follows:

for i in range(100,10**10):  # 不含10**10,终值为9999999999
    s = 0                # 求和初值取“0”
    n = len(str(i))      # 获取数值i的位数
    for j in str(i):     # str(123)='123',则j='1','2','3'
        s += int(j) ** n # 求各位数的n次方和
    if s == i:           # n位阿姆斯特朗数的判断条件
        print(f'{n}位阿姆斯特朗数:', i)

Results of the:

    Although this program is simple, the output effect is not very satisfactory, and the Armstrong numbers with the same number of digits are not displayed in the same line. This program involves 10 billion times of 10-digit 10-billion power calculations, so it will take several hours (a few seconds before 7 digits, 1~2 minutes before 8 digits, 10~30 minutes before 9 digits )

    Next, the program is improved, and the Armstrong numbers with different digits are marked with "aliases", and the Armstrong numbers with the same digits are displayed in the same line, but the time consumption is basically the same. The following program uses ternary expressions.

    The ternary expression is also called the ternary operator. The grammatical format of the ternary expression in Python is:

expression 1 if conditional expression else expression 2

    When the "conditional expression" is True, the return result is "expression1", otherwise the return result is "expression2".

    The syntax for getting a list of dictionary "keys" is:

list ( dict.keys ())

    The complete procedure is as follows:

ArmstrongNum = {'三':'水仙花','四':'四叶玫瑰','五':'五角星','六':'六合',
            '七':'北斗七星','八':'八仙','九':'九九重阳','十':'十全十美'}
for i in range(2,10):
    print(f'{list(ArmstrongNum.keys())[i-2]}位的'
          f'{ArmstrongNum[list(ArmstrongNum.keys())[i-2]]}数:', end='')
    m = 0
    for j in range(10**i, 10**(i+1)):	# 1后跟i个0到 i+1个9
        n = len(str(j))					# n = i + 1,数值j的位数
        s = 0
        for k in str(j):				# str(123)='123',k='1','2','3'
            s += int(k) ** n			# 求各位的n次方和
        if s == j:						# n位阿姆斯特朗数的判断条件
            print(j if m==0 else f', {j}', end='')
            m += 1
    print()

Results of the:

3. Solve the chicken problem

    Zhang Qiujian, an ancient mathematician in China, put forward a mathematical problem in the book " Suan Jing ": a rooster is worth five dollars, a hen mother is worth three dollars, and a chick is worth three dollars. If you buy a hundred chickens for a hundred dollars , how much are the rooster , hen mother , and chicks ?

    Example 2 Hundred chickens problem : (Translation in vernacular) There is a person who has one hundred coins and plans to buy one hundred chickens. When I went to the market, a rooster cost five yuan, a hen cost three yuan, and a chicken cost three chickens. How can I buy a hundred chickens for exactly one hundred yuan? . Now, please write a program to help him plan.

    Note: Chickens are all whole, and the total amount of money is also an integer . Because the money spent to buy roosters and hens is an integer, the money to buy chickens must also be an integer, so the number of chickens is a multiple of 3.

    Let the number of roosters be rooster and the number of hens be hen, then the number of chicks is

chicken = 100-rooster-hen

    One hundred dollars can buy up to 20 roosters, and one hundred dollars can buy up to 33 hens. The specific program code is as follows:

for rooster in range(21):			# 公鸡0~20,不包含21
    for hen in range(34):			# 母鸡0~33,不包含34
        chicken = 100-rooster-hen	# 求小鸡数
        if rooster * 5 + hen * 3 + chicken/3 == 100:
            print(f'公鸡{rooster}只+母鸡{hen}只+小鸡{chicken}只=100只鸡。')

The output is:

 

Program optimization:

    Idea: Let the number of roosters be x, the number of hens be y, and the number of chicks be z, then

    

    Two equations and three variables cannot be solved directly and are indeterminate equations .

    Every time the program uses a for(x) loop, it is equivalent to changing an unknown (x) into a known number (x). Two equations and two unknowns, the equation is solvable, so you can continue to reduce one Nesting of loops. Then solve equation ①② to get

    

The problem can be solved with one loop.

for x in range(21):							# 0~20,不包含21。公鸡数不会超过20
    y = int(25-7*x/4) if 25 >= 7*x/4 else 0	# 先求y(母鸡数为整数且大于等于0)
    z = 100-x-y								# 再求z
    if x * 5 + y * 3 + z / 3 == 100:
        print(f'公鸡{x}只+母鸡{y}只+小鸡{z}只=100只鸡。')

The output is:

Guess you like

Origin blog.csdn.net/hz_zhangrl/article/details/129442726