这篇文章主要介绍了鸡兔同笼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−21my=21m−n
据此,我们可以写出以下函数进行该问题的求解:文章来源:https://www.toymoban.com/news/detail-854430.html
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.')
最后的结果如下:文章来源地址https://www.toymoban.com/news/detail-854430.html
There are 23 chicken.
There are 12 rabbits.
方法一:通过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−21my=21m−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.
到了这里,关于鸡兔同笼python程序怎么写,鸡兔同笼python多种方法的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!