赞
踩
这篇文章主要介绍了鸡兔同笼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\{
- 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 版权所有,并保留所有权利。