## current position：Home>Getting Started with Interesting Algorithms in Python Develop Paper

# Getting Started with Interesting Algorithms in Python Develop Paper

2022-11-08 03:33:31【please call me】

### Problem description

Ancient Chinese mathematician Zhang Qiujian proposed a famous "hundred-money-hundred-chicken problem" in his "Suanjing": a rooster is worth five coins, a hen is worth three coins, and three chicks are worth three coins.It's worth a penny, and now I want to buy a hundred chickens with a hundred dollars. How many roosters, hens, and chicks are there?

### Analysis

This is also a classic problem. In mathematics, it is just a system of multivariate linear equations.If we use cock to represent the number of roosters, hen to represent hens, and chicken to represent chickens, the equations can be listed as follows:

If you use computer thinking, because the amount of data is small (less than 100), you can use the exhaustive method to use three levels of nested loops to represent the number of roosters, hens, and chicks from the outside to the inside, and then judge the three in turn.Whether the value of either satisfies the above two equations at the same time.

Because 100 dollars can buy at most a rooster, hen, a chicken, so the upper limits of these three variables are 20, 33,300.But at the same time, you can't use all the money to buy roosters, hens, and chickens - because the number is wrong, the values are up to 19, 32, and 297 respectively (the number of chickens must be divisible by 3), so you can write the code as follows:

`for cock in range(20):for hen in range(33):for chicken in range(298):if cock+hen+chicken=100 and 5*cock+3*hen+chicken/3==100:print(f"Buy {cock} rooster, {hen} hen, {chicken} chick"`

Of course, this is just an exhaustive method under the most basic computer thinking. If we substitute a little mathematical knowledge, we will find that any one of cock, hen, chicken can be obtained from the other two, such as

img alt="chicken = 100-cock-hen" class=mathcode src="//img.inotgo.com/imagesLocal/202211/08/202211080319247296_9.gif">, so there is no need for three layers of loops at all, as long asKnowing cock and hen, the number of chickens can be obtained according to Equation 1.In addition, since the upper limit of chicken is the largest (297), eliminating the loop of chicken will greatly reduce the number of loops and improve efficiency. Therefore, the code can be modified as follows:

`for cock in range(20):for hen in range(33):chicken = 100-cock-henif 5*cock+3*hen+chicken/3==100:print(f"Buy {cock} rooster, {hen} hen, {chicken} chick"`

The answer is the same, indicating that the program achieves the same effect, but the efficiency is greatly improved.

It's not over yet.

Through mathematical thinking, we can further find that the variable chicken can be eliminated by multiplying both sides of Equation 2 by 3 and then subtracting Equation 1.

Get a new equation:

Divide both sides by 2 to get:

The number of hens can then be obtained from the number of roosters: , and the second layer of loop can also be omitted.

At the same time, looking at this hen equation, the right side is the number of roosters divided by 4, and common sense tells us that the number of hens must be

- is an integer
- greater than 0

Therefore, the number of cocks must be an integer multiple of 4, and .The number of cock itself must also be an integer, so the value range of cock is

Therefore, we can write code to only exhaustively enumerate the number of cocks in this range, the number is greatly reduced, 0, 4, 8, 12, and the computational efficiency is greatly improved.The only thing to note is that because of the introduction of division (7/4), the result obtained automatically becomes floating-point data. Even if it can be divided evenly, the result is displayed as x.0.And we want to output an integer, so here we can use int() to convert the calculation result to an integer type, or use the integer division operator (//) directly.

`for cock in range(0,14,4):hen = 25-int(cock*7/4):chicken = 100-cock-henif 5*cock+3*hen+chicken/3==100:print(f"Buy {cock} rooster, {hen} hen, {chicken} chick"`

### Output

`Buy 0 roosters, 25 hens, 75 chicksBuy 4 roosters, 18 hens, 78 chicksCan buy 8 roosters, 11 hens, 81 chicksBuy 12 roosters, 4 hens, 84 chicks`

Actually, when we use mathematical knowledge to manually complete the above calculations, the obtained solutions (the number of roosters 0, 4, 8, 12) must be reasonable, and no further verification is required. It can be seen that the code is used here.Instead, it seems superfluous and superfluous.This is the difference between computer thinking and mathematical thinking.Computer thinking seems simple, but it is better than the speed of operation, and mathematical thinking can always find solutions to problems faster and more subtly, sometimes without even using computer thinking.What we need to do is to combine the two when faced with different problems, learn from each other's strengths and complement each other's weaknesses, and strive to solve the problem with the highest efficiency.

copyright notice

author[please call me],Please bring the original link to reprint, thank you.

https://en.pythonmana.com/2022/312/202211080319247296.html

## The sidebar is recommended

- python3.7scrapy install scrapy with pip command
- python3.7 'pip3' is not an internal or external command, nor is it a runnable program or batch file
- How to use filters and algorithms to restore pictures and decontaminate pictures in image processing/computer vision/python environment [with code]
- Image processing/computer vision/python environment/machine learning k-nearest neighbor method (KNN), template matching algorithm for data set recognition
- Python from entry to practice - 02 list of basic data types
- Python from entry to practice----01 basic data types
- Image processing/computer vision/python environment/how to deal with noise with four different filters [with code, effective for personal testing]
- Private and public members in python
- Python learning functions, lists and tuples, dictionaries
- How to install python3.11 on windows and use python3.11 to run a quantitative trading strategy written by backtrader and increase the speed by about 20%?

## guess what you like

Mastering Python in 100 Days (Data Analysis) - Day 63: Pandas Using Custom Function Cases

"Python core technology and actual combat" indispensable custom functions and anonymous functions [functional programming important map(), filter(), reduce()]

Is it hard to make games in Python - let's see how much fun I make

The most complete in history - Python installation tutorial

#Scientific Research Foundation# Python Beginner's Notes for Self-Use Part 4 Tuples, Dictionaries and Sets

#Scientific research building base# Python beginner's self-use notes Part 3 Conditional Statements and Loop Statements

Nested loop in Python

openGauss 2.1.0 upgrade 3.1.0 encountered Exception: [GAUSS-52200] : When compiling python error

Selenium+python to do web-side automated testing framework and example detailed tutorial

Python Regular Expression

## Random recommended

- I wrote a financial data crawler in Python, and I did the work of the interns for a week in half an hour
- Python project combat - bank ATM system (3)
- Python decimal to binary function_python hexadecimal to binary
- Python toolbox series (12)
- python automatic send mail script
- [Study Notes] Introduction to Deep Learning: Theory and Implementation Based on Python
- How python handles program exceptions
- Python Volunteer Management System Based on PHP+MySQL
- python is based on PHP+MySQL university asset management system
- Python is based on PHP+MySQL reading sharing platform
- Python student association management system based on PHP+MySQL
- Notes for python importing other modules under windows
- What exactly does Python's __pycache__ cache?Can the historical running results be cached?- A little research on PyCache
- Compare similarity of two vectors - python
- Boutique flower sales shopping mall applet based on Python
- python get all files in current directory
- python gets computer CPU, motherboard, BIOS, hard disk serial number, host name, IP, Mac address
- python get computer unique identifier
- Python converts strings to hexadecimal (encryption and decryption)
- python based on PHP+MySQL college students job recruitment website
- Linear sieve prime number template (Python/C++)
- python university student health management system based on PHP+MySQL
- Python Deep Learning in Action: Testing Neural Networks
- UE4 gets HTTP interface data (UE4 communicates with python)
- Ask a complex text processing problem Python
- Talking about list creation and list element addition and deletion in Python
- Python finds the average mutual information of English text
- Python performance optimization example exercise
- python script rewrite yaml
- Python NotImplementedError: cannot instantiate 'PosixPath' on your system
- How far can a Python novice learn to do automation?
- [Bluebridge Cup for Python] day_008: Huffuman tree
- Install the GDAL library in Python
- Python classic questions finishing
- Python - function design and use
- October 2022 Python Cabin Programming Contest Winners List (Free 5 Books)
- Introduction to Python Interesting Algorithms - Newton's Iterative Method to Find Equation Roots
- Introduction to Python Fun Algorithms - Catch Traffic Accidents & Best Deposit Schemes
- Python writes a small game: snake chess (below)
- Introduction to Python Interesting Algorithms - Rabbit Childbirth (Intrinsic Logic of Fibonacci Sequences)