python

用递归函数计算n的阶层

python 复制代码
def fac(n):
    if n==1:
        return 1
    else:
        return n*fac(n-1)

print(fac(5))

斐波那契函数

python 复制代码
def fac(n):
    if n==1 or n==2:
        return 1
    else:
        return fac(n-1)+fac(n-2)
print(fac(9))

for i in range(1,10):
    print(fac(i),end='\t')
print()#这一个不能与前一个print对齐
#结果为:1	1	2	3	5	8	13	21	34

常用的数据类型转化函数

bool------跟0有关的还有空的类型布尔值都是False

python 复制代码
print('绝对值:',abs(100),abs(-100),abs(0))
print('商和余数:',divmod(13,4))
print('最大值:',max('hello'))
print('最大值:',max([10,4,56,78,4]))
print('最小值:',min('hello'))
print('最小值:',min([10,4,56,78,4]))

print('求和',sum([10,34,45]))
print('x的y次幂:',pow(2,3))

print(round(3.1415926))#3
print(round(3.9415926))#4
print(round(3.1415926,2))#2表示保留两位小数
print(round(313.415926,-1))#-1位,个数进行四舍五入
python 复制代码
lst=[54,56,77,4,56,34]
#(1)排序操作
asc_lst=sorted(lst)#升序
desc_lst=sorted(lst,reverse=True)#降序
print('原列表:',lst)
print('升序:',asc_lst)
print('降序:',desc_lst)

#(2)reversed 逆序
new_lst=reversed(lst)
print(type(new_lst))#class 'list_reverseiterator'>迭代器对象
print(list(new_lst))

#(3)zip
x=['a','b','c','d']
y=[10,20,30,40,50]
zipobj=zip(x,y)
print(type(zipobj))#<class'zip'>
#print(list(zipobj))#[('a', 10), ('b', 20), ('c', 30), ('d', 40)]
#为元组

#(4)enumerate
enum=enumerate(y,start=1)
print(type(enum))
print(tuple(enum))

#(5)all
lst2=[10,20,30,'']
print(all(lst2))#False,只要有空字符串就位False
print(all(lst))#True

print('-'*20)
#(6)any
print(any(lst2))#True,列表元素的所有值都为False的时候为False

#(7)
#运行时需要将19行的代码注释掉
print(next(zipobj))#('a', 10)
print(next(zipobj))#('b', 20)
print(next(zipobj))#('c', 30)
#运行一次获取一次

def fun(num):
    return num%2==1
obj=filter(fun,range(10))#将range中产生的0~9的数字都执行一遍fun操作
print(list(obj))
#[1, 3, 5, 7, 9]#得到的是奇数

def upper(x):
    return x.upper()

new_lst2=['hello','world','python']
obj2=map(upper,new_lst2)
print(list(obj2))
#['HELLO', 'WORLD', 'PYTHON']
#可以像这样用函数代替遍历循环
python 复制代码
print(format(3.14,'20'))#数值默认右对齐
print(format('hello','20'))#字符串默认左对齐
print(format('hello','*<20'))
print(format('hello','*>20'))
print(format('hello','*^20'))


print(format(3.1415926,'2f'))
print(format(20,'b'))
print(format(20,'o'))
print(format(20,'x'))
print(format(20,'X'))

print('-'*40)
print(id(10))
print(id('helloworld'))
print(type('hello'),type(10))

print(eval('10+30'))
print(eval('10>30'))#False
相关推荐
依然鸣2 分钟前
PTA团体程序设计天梯赛L1真题讲解L1-077-080
开发语言·c++·算法·深度优先·pat考试·图论
麻雀飞吧1 小时前
零基础选量化工具,先把问题说清楚
人工智能·python
段一凡-华北理工大学1 小时前
AI推动工业智能化转型~系列文章20:工业 AI 平台架构:云-边-端协同的技术体系
人工智能·python·架构·工业平台·云-边协同
CodeBlog-star1 小时前
Harness Engineering:Pi Agent 架构深度解析
人工智能·python·架构·harness工程
简不变1 小时前
将components下的文件夹复制到别一个文件夹下,并重新生成CMakelist.txt文件
python
库玛西2 小时前
现代 C++ 智能指针全景指南:从 RAII 思想到工业级实践
c语言·开发语言·c++·笔记·面试
AC赳赳老秦2 小时前
风控岗应用:OpenClaw 采集公开司法与经营异常数据,自动生成企业风险评估报告
大数据·c语言·数据库·人工智能·python·php·openclaw
databook2 小时前
如何对稀疏数据的场景进行分析
python·数据挖掘·数据分析
liulilittle2 小时前
无锁并发容器的设计与实现原理
开发语言·c++·set·map·并发·无锁·lock-free
朋克洛德的码农3 小时前
Go并发-sync包四剑客:Mutex、RWMutex、WaitGroup、Once-从入门到原理
开发语言·后端·golang