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}个")
相关推荐
basketball6162 分钟前
使用pytorch保存和加载预训练的模型方法
人工智能·pytorch·python
androidwork16 分钟前
Kotlin Android工程Mock数据方法总结
android·开发语言·kotlin
蓑笠翁00121 分钟前
Python异步编程入门:从同步到异步的思维转变
linux·前端·python
吃货界的硬件攻城狮27 分钟前
【STM32 学习笔记】ADC数模转换器
笔记·stm32·单片机·学习
程序员Bears29 分钟前
Django进阶:用户认证、REST API与Celery异步任务全解析
后端·python·django
codefly-xtl29 分钟前
责任链设计模式
java·开发语言·设计模式
非晓为骁42 分钟前
【Go】优化文件下载处理:从多级复制到零拷贝流式处理
开发语言·后端·性能优化·golang·零拷贝
菜鸟破茧计划43 分钟前
C++ 算法学习之旅:从入门到精通的秘籍
c++·学习·算法
北极象1 小时前
Golang中集合相关的库
开发语言·后端·golang
海尔辛1 小时前
学习黑客 MAC 地址深入了解
学习·macos·php