1. 程式人生 > >python 實現算法

python 實現算法

pri http append [] res pen image print num

斐波那鍥數列

def fib(num):
    a = 0
    b = 1
    n = 0
    while n < num:
        a, b = b , a + b
        yield a
        n += 1
    print('done')

for i in fib(9):
    print(i)
print(fib(9))

技術分享圖片

楊輝三角

def triangles(num):
    l = []
    n = 0
    c = 0
    while n < num:
        b = 0
        result = []
        if len(l):
            for x in l[:]:
                result.append(b + x)
                b = x
            l = result[:]
        l.append(1)
        yield l
        n += 1
    print('done')

for val in triangles(9):
    print(val)

技術分享圖片

python 實現算法