Construct program logic
After learning the previous chapters, I think it is necessary to take you to do some exercises here to consolidate the previous knowledge. Although what we have learned so far is only the tip of the iceberg of python, these contents are enough for us to build the logic in the program. For beginners of programming language, after learning the core language elements of python (variables, types, operators, expressions, branch structures, loop structures, etc.), one thing they must do is to try to use their knowledge to solve real problems, in other words, to exercise their algorithms described in human natural language (Methods and steps to solve problems) The ability to translate into Python code, which must be achieved through a lot of practice.
In this chapter, we have sorted out some classic cases and exercises for you. We hope that these examples can help you consolidate the Python knowledge you have learned before, and help you understand how to establish the logic in the program and how to use some simple algorithms to solve real problems.
Classic example
-
Look for daffodils.
Note: narcissus number is also called super complete number invariant number, narcissistic number, self idempotent number and Armstrong number. It is a three digit number. The sum of the cubes of the numbers in each digit is exactly equal to itself, for example: 1 3 + 5 3 + 3 3 = 153 1^3 + 5^3+ 3^3=153 13+53+33=153.
""" Find out the number of all daffodils Version: 0.1 Author: Luo Hao """ for num in range(100, 1000): low = num % 10 mid = num // 10 % 10 high = num // 100 if num == low ** 3 + mid ** 3 + high ** 3: print(num)
In the above code, we find out a three digit single digit, ten digit and hundred digit respectively through integer division and modulo operation. This little skill is still commonly used in practical development. Using a similar method, we can also reverse a positive integer, for example, from 12345 to 54321. The code is as follows.
""" Inversion of positive integers Version: 0.1 Author: Luo Hao """ num = int(input('num = ')) reversed_num = 0 while num > 0: reversed_num = reversed_num * 10 + num % 10 num //= 10 print(reversed_num)
-
A hundred dollars and a hundred chickens.
Explanation: a hundred money and a hundred chickens are ancient mathematicians in China Qiu Jian Zhang The mathematical problems put forward in the book "Suanjing": a chicken Weng is worth five, a chicken mother is worth three, and a chicken chick is worth three. If you buy a hundred chickens for a hundred dollars, ask the chicken owner, the chicken mother and the chicken chick? A rooster is 5 yuan a, a hen is 3 yuan a, and a chick is 1 yuan three. Buy 100 chickens with 100 yuan. Ask how many roosters, hens and chicks are there?
""" <A hundred dollars and a hundred chickens Version: 0.1 Author: Luo Hao """ for x in range(0, 20): for y in range(0, 33): z = 100 - x - y if 5 * x + 3 * y + z / 3 == 100: print('cock: %d only, hen: %d only, chick: %d only' % (x, y, z))
The method used above is called exhaustive method, also known as violent search method. This method lists all possible candidates in alternative solutions one by one, and checks whether each candidate meets the description of the problem, so as to finally get the solution of the problem. This method looks clumsy, but it is usually a feasible or even good choice for computers with very powerful computing power, and if the solution of the problem exists, this method will be able to find it.
-
CRAPS gambling game.
Description: CRAPS, also known as Citi dice, is a very popular table gambling game in Las Vegas. The game uses two dice. Players get points by shaking two dice. The simple rule is: if the player shakes the dice for the first time, if he shakes out 7 or 11 points, the player wins; If the player shakes 2, 3 or 12 points for the first time, the dealer wins; Other points players continue to roll dice. If the player rolls out 7 points, the dealer wins; If the player shakes the points for the first time, the player wins; For other points, the player continues to dice until the winner is determined.
""" Craps Gambling games We set a bet of 1000 yuan when the player starts the game The condition for the end of the game is that the player loses all his bets Version: 0.1 Author: Luo Hao """ from random import randint money = 1000 while money > 0: print('Your total assets are:', money) needs_go_on = False while True: debt = int(input('Please bet: ')) if 0 < debt <= money: break first = randint(1, 6) + randint(1, 6) print('The player shakes out%d spot' % first) if first == 7 or first == 11: print('Player wins!') money += debt elif first == 2 or first == 3 or first == 12: print('Zhuang Jiasheng!') money -= debt else: needs_go_on = True while needs_go_on: needs_go_on = False current = randint(1, 6) + randint(1, 6) print('The player shakes out%d spot' % current) if current == 7: print('Zhuang Jiasheng') money -= debt elif current == first: print('Player wins') money += debt else: needs_go_on = True print('You're broke, game over!')
Useful exercises
-
Generate the first 20 numbers of Fibonacci sequence.
Note: Fibonacci sequence, also known as the golden section sequence, is a sequence introduced by the Italian mathematician Leonardo Fibonacci in his book of calculation, which puts forward the problem of rabbit growth rate under ideal assumptions. Therefore, this sequence is also jokingly called "rabbit sequence". The characteristic of Fibonacci sequence is that the first two numbers of the sequence are 1. Starting from the third number, each number is the sum of its first two numbers, such as 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144. Fibonacci sequence has direct applications in modern physics, quasicrystal structure, chemistry and other fields.
-
Find the perfect number within 10000.
Note: perfect number is also called perfect number or complete number. The sum of all its true factors (i.e. factors other than itself) (i.e. factor function) is exactly equal to itself. For example: 6( 6 = 1 + 2 + 3 6=1+2+3 6 = 1 + 2 + 3) and 28( 28 = 1 + 2 + 4 + 7 + 14 28=1+2+4+7+14 28 = 1 + 2 + 4 + 7 + 14) is the perfect number. Perfect number has many magical features. Those who are interested can understand it by themselves.
-
Output all primes within 100.
Note: prime numbers refer to positive integers (excluding 1) that can only be divided by 1 and itself.
The reference answers of the above exercises are in the corresponding code directory of this chapter. If you need help, please check the reference answers by yourself.