please call me 2022-11-08 03:33:31 阅读数:368

gettingstartedinterestingalgorithmspython

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?

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"`

`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.

版权声明：本文为[please call me]所创，转载请带上原文链接，感谢。 https://pythonmana.com/2022/312/202211080319247296.html

- 图解Python编程：从入门到精通系列教程（附全套速查表）
- 【开源分享】基于Python+OpenCV+PyQt5车牌识别(GUI界面)
- 基于Python+OpenCV车道线检测(直道和弯道)
- python每日一题【剑指 Offer 20. 表示数值的字符串】
- python每日一题【剑指 Offer 59 - II. 队列的最大值】
- python每日一题【剑指 Offer 35. 复杂链表的复制】
- 每日一题python【剑指 Offer 59 - I. 滑动窗口的最大值】
- python每日一题【剑指 Offer 58 - II. 左旋转字符串】
- python每日一题【剑指 Offer 30. 包含 min 函数的栈】
- python每日一题【剑指 Offer 24. 反转链表】
- 每日一题python【剑指 Offer 09. 用两个栈实现队列】
- 浅谈Python中列表创建与列表元素增删
- Talking about list creation and list element addition and deletion in Python
- Leetcode第3题 无重复字符的最长子串lengthOfLongestSubstring（附java和python代码）
- LeetCode第5题 最长回文子串longestPalindrome（附java和python代码）
- LeetCode 第10题正则表达式匹配isMatch（java＆python实现）
- Leetcode 第6题 Z 字形变换convert（附java和python代码）
- python 常用包-用pip install -r requirements.txt导入
- LeetCode 第2题两数相加（附java和python代码）
- LeetCode 第8题目 字符串转换整数 (myAtoi)（附java和python代码）
- LeetCode 第7题整数反转reverse（附java和python代码）
- 读书笔记：python+vue实战派
- python 生成本地项目特定文件夹下依赖文件 requirements.txt 的方式
- 特定文件夹下 简单安装隔离的 python 虚环境
- python 性能优化实例练习
- Python求英文文本的平均互信息
- Python-Flask快速上手
- Python牛客刷题笔记
- Python finds the average mutual information of English text
- python脚本重写yaml
- Python NotImplementedError: cannot instantiate ‘PosixPath‘ on your system
- Python小白学习到什么程度才可以做自动化
- 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?
- python-(6-3-1)爬虫---requests入门
- 关于python序列对象浅谈
- Python定义函数
- Python语法入门介绍
- Python中安装GDAL库
- 【Python 之 Bluebridge Cup】day_008：Huffuman树
- 2022年10月Python小屋编程比赛获奖名单（送5本书）
- Python——函数设计与使用
- Python经典题整理
- Python写个小游戏：蛇棋（下）
- Python趣味算法入门 - 借书方案知多少
- Python趣味算法入门 - 抓交通肇事犯 ＆ 最佳存款方案
- Python趣味算法入门 - 牛顿迭代法求方程根
- Python趣味算法入门 - 百钱百鸡
- Python趣味算法入门 - 兔子产子（斐波那契数列的内在逻辑）
- [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)