首页 > 代码库 > 杨辉三角实现

杨辉三角实现

1   # -*- coding: utf-8 -*-

def triangles():
    line = [1]
    while True:
        yield line
        line = [x + y for x, y in zip([0] + line, line + [0])]

n = 0
for t in triangles():
    print(t)
    n = n + 1
    if n == 10:
        break

2

def triangles1(): # 杨辉三角形 L = [1] while True: yield L L = [1] + [L[n] + L[n-1] for n in range(1, len(L))] + [1]

def triangles2(): # 杨辉三角形 L = [1] while True: yield L L = [L[n - 1] + L[n] for n in range(len(L))]

def triangles3(): # 杨辉三角形 L = [1] while True: yield L for n in range(1, len(L)): L[n] = pre[n] + pre[n - 1] L.append(1) pre = L[:]

n = 0 for t in triangles1(): # 直接修改函数名即可运行 print(t) n = n + 1 if n == 10: break

3

def triangles():
i = 1
L = [1]
while True:
yield L
L = [0] + L + [0]
L = [L[s]+L[s+1] for s in range(i+1)]
i += 1
n = 0
for t in triangles():
print(t)
n += 1
if n == 10:
break

 

 

4

 

 


def triangles():
    l = []
    while True:
        last = 0
        lr = []
        for i in l:
            lr.append(last + i)
            last = i
        lr.append(1)
        l = lr
        yield lr

杨辉三角实现