赞
踩
方法一:通过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\{
得到的解为:
{
x
=
2
n
−
1
2
m
y
=
1
2
m
−
n
\left\{
据此,我们可以写出以下函数进行该问题的求解:
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.
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。