如何用Python编写鸡兔同笼问题的程序?多种解法分享

这篇文章主要介绍了鸡兔同笼python程序怎么写,具有一定借鉴价值,需要的朋友可以参考下。希望大家阅读完这篇文章后大有收获,下面让小编带着大家一起了解一下。

Source code download: 本文相关源码

方法一:通过sympy的方法进行计算

from sympy import Symbol,solve,pprint
x = Symbol('x')
y = Symbol('y')
n = Symbol('n')
m = Symbol('m')
expr1 = x + y - n
expr2 =2*x+4*y- m
solution = solve((expr1,expr2),(x,y),dict=True)
chicken = solution[0][x].subs({n:35,m:94})
rabbits = solution[0][y].subs({n:35,m:94})
print(f'There are {chicken} chicken.')
print(f'There are {rabbits} rabbits.')

结果如下:

There are 23 chicken.
There are 12 rabbits.

方法二:通过解析式编写函数求解
假设有 x x x只鸡, y y y只兔子,我们可以列出以下方程组:
{ x + y = n 2 x + 4 y = m \left\{ \begin{aligned} &x+y = n \\ &2x+4y = m \\ \end{aligned} \right. {​x+y=n2x+4y=m​
得到的解为:
{ x = 2 n − 1 2 m y = 1 2 m − n \left\{ \begin{aligned} &x = 2n-\frac{1}{2}m \\ &y = \frac{1}{2}m-n \\ \end{aligned} \right. ⎩⎪⎨⎪⎧​​x=2n−21​my=21​m−n​
据此,我们可以写出以下函数进行该问题的求解:

def chicken_and_rabbits(nheads,mlegs):
	rabnum = mlegs/2 - nheads
	chinum = 2*nheads - mlegs/2
	return chinum,rabnum

chicken = int(chicken_and_rabbits(35,94)[0])
rabbits = int(chicken_and_rabbits(35,94)[1])

print(f'There are {chicken} chicken.')
print(f'There are {rabbits} rabbits.')

最后的结果如下:

There are 23 chicken.
There are 12 rabbits.
物联沃分享整理
物联沃-IOTWORD物联网 » 如何用Python编写鸡兔同笼问题的程序?多种解法分享

发表评论