This article is included inPython from introduction to Mastery Series
After learning the previous chapters, the blogger thinks it is necessary to take you to do some exercises here to consolidate the previous knowledge. Although the content we have learned so far is just the tip of the iceberg of python, it is enough for us to build the logic in the program. For beginners of programming languages, after learning Python’s core language elements (variables, types, operators, expressions, branch structures, loop structures, etc.), one of the things they must do is try to use the knowledge they have learned to solve problems in reality. In other words, exercise their own algorithms described in human natural languages (Methods and steps to solve problems ）The ability to translate into Python code, which can only be achieved through a lot of practice.
The blogger sorts out some classic cases and exercises for you in this chapter, hoping that through these examples, on the one hand, they can help you consolidate the python knowledge you have learned before, on the other hand, they can help you understand how to build the logic in the program and how to use some simple algorithms to solve the problems in reality.
Warning: This article is very brain burning, it is recommended to watch it above the age of 18; under the age of 18, it is recommended to watch it with parents!!! (ha ha ha, make a joke ~)
1. Classic examples
1.1 find the number of Narcissus.
Note: narcissus number is also known as super perfect 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 $.
""" Find all daffodils Version: 0.1 Author: along """ 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(low,mid,high) print(num)
In the above code, we find a three digit one digit, ten digit and hundred digit respectively through integer division and modular operation, which is still commonly used in actual development.
1.2 inverting a positive integer
In a similar way, we can also reverse a positive integer, for example, change 12345 to 54321, as shown below.
""" Inversion of positive integers Version: 0.1 Author: along """ num = int(input('num = ')) reversed_num = 0 while num > 0: reversed_num = reversed_num * 10 + num % 10 num //= 10 #print(reversed_num,num) print(reversed_num)
1.3 100 yuan and 100 chickens
Explanation: hundred money and hundred chickens is a mathematical problem put forward by Zhang Qiujian, an ancient mathematician of China, in the book of calculation: one chicken is worth five, one chicken mother is worth three, and three chickens are worth one. To buy a hundred chickens for a hundred bucks, ask the chicken Weng, the hen mother and the chicks how much are they? A rooster is 5 yuan, a hen is 3 yuan, and a chick is 1 yuan. How many chickens do you have for 100 yuan?
""" The problem of "a hundred money and a hundred chickens" Version: 0.1 Author: along """ for x in range(0,20): for y in range(0,33): z = 100 - x - y if 100 == 5 * x + 3 * y + z / 3: Print ('cock:% D, hen:% D, chick:% d '% (x, y, z))
The method used above is calledExhaustive methodAlso known asViolent searchThis method enumerates all possible candidates in the alternative solution one by one and checks whether each candidate conforms to the description of the problem to get the solution of the problem finally. This method seems to be clumsy, but it is usually a feasible or even a good choice for computers with very powerful computing power. Moreover, if the solution of the problem exists, this method can find it.
1.4 craps gambling game
Explanation: craps, also known as citidice, is a very popular table game in Las Vegas. The game uses two dice. Players can get points by rolling two dice. The simple rule is: if the player rolls 7 or 11 dice for the first time, the player wins; if the player rolls 2, 3 or 12 dice for the first time, the banker wins; if the player rolls 7 dice, the banker wins; if the player rolls the points for the first time, the player wins; if the player rolls other points, the player continues to ask for dice until the winner wins.
""" Craps gambling game We set the player to start the game with a 1000 yuan bet The end of the game is when the player loses all his bets Version: 0.1 Author: along """ 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 ('player shakes out% d points'% first) if first == 7 or first == 11: Print ('player wins! ') money += debt elif first == 2 or first == 3 or first == 12: Print ('dealer wins! ') money -= debt else: needs_go_on = True while needs_go_on: needs_go_on = False current = randint(1, 6) + randint(1, 6) Print ('player shakes out% d points'% current) if current == 7: Print ('dealer wins') money -= debt elif current == first: Print ('player wins') money += debt else: needs_go_on = True Print ('You're broke, the game's over! ')
Note: This is too brain burning. The blogger has gone bankrupt
2. Useful exercises
2.1 generate the first 20 numbers of Fibonacci series.
Explanation: Fibonacci sequence, also known as golden section sequence, is a sequence introduced by Italian mathematician Leonardo Fibonacci in the book of calculation, which puts forward a problem of rabbit growth rate under the ideal assumption. Therefore, this sequence is also known as “rabbit sequence”. Fibonacci sequence is characterized by that the first two numbers of the sequence are all 1. Starting from the third number, each number is the sum of the first two numbers, such as: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144. Fibonacci sequence has direct application in modern physics, quasicrystal structure, chemistry and other fields.
""" Output the first 20 numbers of Fibonacci series 1 1 2 3 5 8 13 21 ... Version: 0.1 Author: along """ a = 0 b = 1 for _ in range(20): a, b = b, a + b print(a, end=' ')
2.2 find the perfect number within 10000.
Note: perfect number is also called complete 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 $) and 28 ($28 = 1 + 2 + 4 + 7 + 14 $) are perfect numbers. Perfect number has a lot of magical features, and those who are interested can learn about it by themselves.
""" Find all the perfect numbers between 1 and 9999 The perfect number is the sum of all factors except itself, which is exactly equal to the number itself For example: 6 = 1 + 2 + 3, 28 = 1 + 2 + 4 + 7 + 14 Version: 0.1 Author: along """ import math for num in range(1, 10000): result = 0 for factor in range(1, int(math.sqrt(num)) + 1): if num % factor == 0: result += factor if factor > 1 and num // factor != factor: result += num // factor if result == num: print(num)
2.3 output all prime numbers within 100.
Note: prime refers to a positive integer (excluding 1) that can only be divided by 1 and itself.
""" Output prime number between 2 and 99 Version: 0.1 Author: along """ import math for num in range(2, 100): is_prime = True for factor in range(2, int(math.sqrt(num)) + 1): if num % factor == 0: is_prime = False break if is_prime: print(num, end=' ')