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}个")
相关推荐
数据智能老司机4 小时前
精通 Python 设计模式——分布式系统模式
python·设计模式·架构
数据智能老司机5 小时前
精通 Python 设计模式——并发与异步模式
python·设计模式·编程语言
数据智能老司机5 小时前
精通 Python 设计模式——测试模式
python·设计模式·架构
数据智能老司机5 小时前
精通 Python 设计模式——性能模式
python·设计模式·架构
c8i5 小时前
drf初步梳理
python·django
每日AI新事件5 小时前
python的异步函数
python
这里有鱼汤6 小时前
miniQMT下载历史行情数据太慢怎么办?一招提速10倍!
前端·python
databook15 小时前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室15 小时前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三17 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试