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 小时前
Java中断
java·开发语言
施棠海5 小时前
监听与回调的三个demo
java·开发语言
時肆4855 小时前
C语言造轮子大赛:从零构建核心组件
c语言·开发语言
赴前尘5 小时前
golang 查看指定版本库所依赖库的版本
开发语言·后端·golang
de之梦-御风5 小时前
【C#.Net】C#开发的未来前景
开发语言·c#·.net
web3.08889995 小时前
微店商品详情API实用
python·json·时序数据库
知乎的哥廷根数学学派6 小时前
基于数据驱动的自适应正交小波基优化算法(Python)
开发语言·网络·人工智能·pytorch·python·深度学习·算法
非凡ghost6 小时前
Wireshark中文版(网络抓包工具)
网络·windows·学习·测试工具·wireshark·软件需求
de之梦-御风6 小时前
【C#.Net】C#在工业领域的具体应用场景
开发语言·c#·.net
sunfove6 小时前
将 Python 仿真工具部署并嵌入个人博客
开发语言·数据库·python