Python 编程题 第四节:斐波那契数列、列表的复制、暂停后输出、成绩评级、统计字符

斐波那契数列

方法一(递归)

python 复制代码
def f(a):
    if a==1:
        return 1
    elif a==2:
        return 1
    else:
        return f(a-1)+f(a-2)
print(f(3))

方法二(非递归)

python 复制代码
n=int(input())
lst=[1,1]
for i in range(2,n+1):
    lst.append(lst[i-1]+lst[i-2])
print(lst[n-1])

列表的复制

这样赋值改变list1也会改变list2,实际上等同于两个指针指向相同的内存地址

python 复制代码
list1=[1,2,3,4]
list2=list1
print(list2)
list1[1]=1
print(list2)

结果

1, 2, 3, 4

1, 1, 3, 4

使用copy库里的deepcopy实现深拷贝

python 复制代码
import copy
list1=[1,2,3,4]
list2=copy.deepcopy(list1)
print(list2)
list1[1]=1
print(list2)

结果

1, 2, 3, 4

1, 2, 3, 4

暂停后输出

time库里的sleep方法,实现暂停后输出,单位是秒

python 复制代码
import time
time.sleep(15)
print("hello world")

成绩评级

python 复制代码
score=int(input())
if score>=90:
    print("A")
elif 60 <= score <=89:
    print("B")
else:
    print("C")

统计字符

python 复制代码
string=input()
char=0
num=0
space=0
other=0
for i in string:
    if i.isalpha():
        char+=1
    elif i.isdigit():
        num+=1
    elif i.isspace():
        space+=1
    else:
        other+=1
print(f"字母有{char}个,数字有{num}个,空格有{space}个,其他字符有{other}个")
相关推荐
dev派39 分钟前
AI Agent 系统中的常用 Workflow 模式(2) Evaluator-Optimizer模式
python·langchain
前端付豪3 小时前
AI 数学辅导老师项目构想和初始化
前端·后端·python
用户0332126663673 小时前
将 PDF 文档转换为图片【Python 教程】
python
悟空爬虫4 小时前
UV实战教程,我啥要从Anaconda切换到uv来管理包?
python
dev派4 小时前
AI Agent 系统中的常用 Workflow 模式(1)
python·langchain
明月_清风6 小时前
从“能用”到“专业”:构建生产级装饰器与三层逻辑拆解
后端·python
曲幽16 小时前
数据库实战:FastAPI + SQLAlchemy 2.0 + Alembic 从零搭建,踩坑实录
python·fastapi·web·sqlalchemy·db·asyncio·alembic
用户83562907805120 小时前
Python 实现 PowerPoint 形状动画设置
后端·python
ponponon1 天前
时代的眼泪,nameko 和 eventlet 停止维护后的项目自救,升级和替代之路
python
Flittly1 天前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(5)Skills (技能加载)
python·agent