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}个")
相关推荐
Leo来编程几秒前
Pycharm常用快捷键总结
ide·python·pycharm
Peter_chq几秒前
selenium快速入门
linux·开发语言·chrome·python·selenium
T - mars4 分钟前
python爬虫:喜马拉雅案例(破解sign值)
javascript·爬虫·python
双叶8365 分钟前
(51单片机)串口通讯(串口通讯教程)(串口接收发送教程)
c语言·开发语言·c++·单片机·嵌入式硬件·microsoft·51单片机
Loving_enjoy15 分钟前
从响应式编程到未来架构革命:解锁高并发时代的底层思维范式
python·ai编程
北京_宏哥35 分钟前
🔥PC端自动化测试实战教程-2-pywinauto 启动PC端应用程序 - 上篇(详细教程)
前端·windows·python
_x_w44 分钟前
【12】数据结构之基于线性表的排序算法
开发语言·数据结构·笔记·python·算法·链表·排序算法
北京_宏哥1 小时前
🔥PC端自动化测试实战教程-1-pywinauto 环境搭建(详细教程)
前端·windows·python
不爱学英文的码字机器1 小时前
Rust 的征服:从系统编程到全栈开发的 IT 新宠
开发语言·后端·rust
grrrr_11 小时前
【ctfplus】python靶场记录-任意文件读取+tornado模板注入+yaml反序列化(新手向)
python·web安全·tornado