Python实现斐波那契数列,九九乘法表,金字塔方法。

斐波那契数列
递归实现,写法最简洁,但是效率最低,会出现大量的重复计算
def function(n):
    assert n >= 0, 'n > 0'
    if n<= 1:
        return n
    return function(n-1) + function(n-2)
print(function(4))
for i in range(0,20):
    print(function(i),end=',')
递推法,递推法,就是递增法,呈线性增长,如果数据量巨大,速度会越拖越慢
def function(n):
    a,b = 0,1
    for i in range(n):
        a,b = b,a+b
    return a
print(function(3))

 生成器实现

def fib(max):
    a,b = 0,1
    while a<max:
        yield a
        a,b = b,a+b
fib_gt=fib(100)
#调用生成器,生成数列
print(next(fib_gt))
print(next(fib_gt))

 

 金字塔
n = int(input('请输入你需要打印星星的层数:'))
for i in range(1, n + 1):
    print(' ' * (n - (i - 1)) + '*' * (2 * i - 1))
 乘法表 方向1
for i in range(1,10):
    for j in range(1,i+1):
        d = i * j
        print('%d*%d=%-2d'%(i,j,d),end = ' ' )
    print()
方向二
def hanshu(n):
    m = n
    sums = 0
    for j in range(1,n+1):
        sums = m*j
        print("%d*%d=%-2d"%(m,j,sums),end = "  ")
    print("")
def hanshu1():
    for i in range(9,0,-1):
        hanshu(i)
hanshu1()
 方向三
def hanshu(n):
    m = n
    sums = 0
    for k in range(0,10-n):
        print("       ",end = "")
    for j in range(1,n+1):
        sums = m*j
        print("%d*%d=%-2d"%(m,j,sums),end = " ")
    print("")

def hanshu1():
    for i in range(1,10):
        hanshu(i)

hanshu1()
方向四
def hanshu(n):
    for dix in range(10-n,0,-1):
        print("       ",end = "")
    sums = 0
    m = n
    for j in range(1,n+1):
        sums = m*j
        print("%d*%d=%-2d"%(m,j,sums),end = " ")
    print("")
def hanshu1():
    for i in range(9,0,-1):
        hanshu(i)
hanshu1()

done。

上一篇:vue+elementUI表格的表尾合计(前端显示后台封装成对象视图层的数据合计详解)


下一篇:洛谷P2802题解