当前位置:   article > 正文

鸡兔同笼问题的python解法_鸡兔同笼python

鸡兔同笼python

在这里插入图片描述

方法一:通过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.')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

结果如下:

There are 23 chicken.
There are 12 rabbits.
  • 1
  • 2

方法二:通过解析式编写函数求解
假设有 x x x只鸡, y y y只兔子,我们可以列出以下方程组:
{ x + y = n 2 x + 4 y = m \left\{

x+y=n2x+4y=m
\right. {x+y=n2x+4y=m
得到的解为:
{ x = 2 n − 1 2 m y = 1 2 m − n \left\{
x=2n12my=12mn
\right.
x=2n21my=21mn

据此,我们可以写出以下函数进行该问题的求解:

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.')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

最后的结果如下:

There are 23 chicken.
There are 12 rabbits.
  • 1
  • 2
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/587640
推荐阅读
相关标签
  

闽ICP备14008679号