python实战训练--基础练习题(2)

斐波那契数列。

斐波那契数列指的是bai这样一个数列 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368…

这个数列从第3项开始,每一项都等于前两项之和。
程序分析: 斐波那契数列(Fibonacci sequence),从1,1开始,后面每一项等于前面两项之和。图方便就递归实现,图性能就用循环。

递归实现

def Fib(n):
    return 1 if n<=2 else Fib(n-1)+Fib(n-2)
print(Fib(int(input('请输入想得知的第?个数:'))))

朴素实现

target=int(input('请输入想得知的第?个数:'))
res=0
a,b=1,1
for i in range(target-1):
    a,b=b,a+b
print(a)

列表copy

题目: 将一个列表的数据复制到另一个列表中。

程序分析 使用列表[:],拿不准可以调用copy模块。

import copy
a = [1,2,3,4,['a','b']]

b = a					# 赋值
c = a[:]				# 浅拷贝
d = copy.copy(a)		# 浅拷贝
e = copy.deepcopy(a)	# 深拷贝

a.append(5)
a[4].append('c')

print('a=',a)
print('b=',b)
print('c=',c)
print('d=',d)
print('e=',e)

结果:

a= [1, 2, 3, 4, ['a', 'b', 'c'], 5]
b= [1, 2, 3, 4, ['a', 'b', 'c'], 5]
c= [1, 2, 3, 4, ['a', 'b', 'c']]
d= [1, 2, 3, 4, ['a', 'b', 'c']]
e= [1, 2, 3, 4, ['a', 'b']]

九九乘法表

i = 0
while i < 9:
    i += 1
    j = 0
    while j < i:
        j += 1
        e = j*i
        print(f'{j}x{i}={e}',end=' ')
    print()

结果:

1x1=1 
1x2=2 2x2=4 
1x3=3 2x3=6 3x3=9 
1x4=4 2x4=8 3x4=12 4x4=16 
1x5=5 2x5=10 3x5=15 4x5=20 5x5=25 
1x6=6 2x6=12 3x6=18 4x6=24 5x6=30 6x6=36 
1x7=7 2x7=14 3x7=21 4x7=28 5x7=35 6x7=42 7x7=49 
1x8=8 2x8=16 3x8=24 4x8=32 5x8=40 6x8=48 7x8=56 8x8=64 
1x9=9 2x9=18 3x9=27 4x9=36 5x9=45 6x9=54 7x9=63 8x9=72 9x9=81 

暂停一秒输出

题目 暂停一秒输出。

程序分析 使用 time 模块的 sleep() 函数。

import time
for i in range(4):
print(str(int(time.time()))[-2:])
time.sleep(1)

给人看的时间

题目 暂停一秒输出,并格式化当前时间。

程序分析 同暂停一秒输出

import time

for i in range(4):
print(time.strftime(’%Y-%m-%d %H:%M:%S’,time.localtime(time.time())))
time.sleep(1)

猜你喜欢

转载自blog.csdn.net/xdc1812547560/article/details/107561275