python常用算法有哪些_python的七个基本算法示例

#七种基本算法:解析算法,枚举算法,递推算法,递归算法,排序算法,查找算法,分治算法

#解析算法

#1.根据定义计算组合数

import math

n, i = input("请输入整数n,i:").split(‘ ‘)

n = int(n)

i = int(i)

b = math.factorial(n) / (math.factorial(i) * math.factorial(n - i))

print(b)

#2.计算一元二次方程的根

def root(a , b , c):

if not isinstance(a, (int, float, complex)) or abs(a) < 1e-6:

print("error")

if not isinstance(b ,(int, float, complex)):

print("error")

if not isinstance(c, (int, float, complex)):

print("error")

d = b ** 2 - 4 * a * c

x1 = (-b + d ** 0.5) / (2 * a)

x2 = (-b - d ** 0.5) / (2 * a)

if isinstance(x1, complex): #complex为复数

x1 = round(x1.real, 3) + round(x1.imag, 3) * 1j #round(x,3)取三位有效数字

x2 = round(x2.real, 3) + round(x2.imag, 3) * 1j

return (x1, x2)

return (round(x1, 3), round(x2, 3))

a, b, c = input("请输入a,b,c:").split(‘ ‘)

a = int(a)

b = int(b)

c = int(c)

r = root(a, b, c)

if isinstance(r, tuple):

print(‘x1 = {0[0]}\nx2 = {0[1]}‘.format(r))

#3.并联电阻的计算(1/R = 1/R1 + 1/R2 + 1/R3 + ... + 1/Rn)

def compute(R_set):

#R_middle = sum([1/r for r in R_set]) 产生列表的两种方法:①列表推导式 ②map + lambda

R_middle = sum(map(lambda x:1/x, R_set))

return 1/R_middle

R_end = round(compute([50, 30,20]), 3)

print(R_end)

#4.根据公式计算圆的面积

import math

def compute_area(r):

return math.pi * r *r

print(round(compute_area(3), 3))

#5.已知三角形的两个边长和夹角角度,计算第三条边长(c**2=a*

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值