《中学生可以这样学Python》P171-176
根据定义计算组合数
#解析算法案例分析
##根据定义计算组合数
import math
def Cni(n,i):
return int(math.factorial(n)/math.factorial(i)/math.factorial(n-i))
print(Cni(10,6))
编写程序,计算一元二次方程的根
##编写程序,计算一元二次方程的根
def root(a,b,c,highmiddle=True):
if not isinstance(a,(int,float,complex)) or abs(a)<1e-6:
print('error')
return
if not isinstance(b,(int,float,complex)):
print('error')
return
if not isinstance(c,(int,float,complex)):
print('error')
return
d=b**2-4*a*c
x1=(-b+d**0.5)/(2*a)
x2=(-b-d**0.5)/(2*a)
if isinstance(x1,complex):
if highmiddle:
x1=round(x1.real,3)+round(x1.imag,3)*1j
x2=round(x2.real,3)+round(x2.imag,3)*1j
return (x1,x2)
else:
return 'no answer'
return (round(x1,3),round(x2,3))
r=root(1,2,4)
if isinstance(r,tuple):
print('x1={0[0]}\nx2={0[1]}'.format(r))
并联电路的电阻计算
##并联电路的电阻计算
def compute(lst):
r=sum(map(lambda x:1/x,lst))
return round(1/r,3)
print(compute([50,30,20]))
根据公式计算圆的面积
##根据公式计算圆的面积
from math import pi as PI
def circleArea(r):
if isinstance(r,(int,float)):
return PI*r*r
else:
return '半径必须为数值'
print(circleArea(3))
已知三角形的两个边长和夹角角度,计算第三边长
##已知三角形的两个边长和夹角角度,计算第三边长
from math import cos,pi
def thirdLength(a,b,C):
C=C/180*pi ##角度C转为弧度C
return (a**2+b**2+2*a*b*cos(C))**0.5
print(thirdLength(3,4,90))
编写程序,执行后用户输入摄氏温度,由程序转换为华氏温度并输出
##编写程序,执行后用户输入摄氏温度,由程序转换为华氏温度并输出
C=input('请输入摄氏温度:')
try:
F=float(C)*1.8+32
print(F)
except:
print('输入不合法')
结果:
>>> %Run test8.py
210
x1=(-1+1.732j)
x2=(-1-1.732j)
9.677
28.274333882308138
5.0
请输入摄氏温度:36.5
97.7