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

斐波那契数列
普通函数实现
#普通函数
def fb(max):
    a,b=0,1
    while a<max:
        print(a)
        a,b=b,a+b

fb(100)

递归实现方法1

def fb1(max,a=1,b=1):
    if a<max:
        print(a)
        fb1(max,b,a+b)
fb1(1000,77,88)

递归实现方法2,写法最简洁,但是效率最低,会出现大量的重复计算
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。

    原文作者:记住我忘记我
    原文地址: https://www.cnblogs.com/nmsghgnv/p/11454815.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞