Discuss / Python / 直到评论区的凶狠解答

直到评论区的凶狠解答

Topic source

lostexin

#1 Created at ... [Delete] [Delete and Lock User]
# 杨辉三角的几何性质: 每个数等于它上方两数之和(前提: 每行端点与结尾的数为 1)

# 初版
def triangles():
    n = 1
    L = [1]

    while True:
        if n == 1:
            n += 1
            yield L
            
        L = [( 1 if ( (not L[:i]) or (not L[i:]) ) else (L[i - 1] + L[i]) ) for i in range(n)]
        n += 1
        yield L
        
# 改进版(利用生成器的特性并且去除 n)
def triangles():
    L = [1]
    yield L
    while True:
        L = [( 1 if ( (not L[:i]) or (not L[i:]) ) else (L[i - 1] + L[i]) ) for i in range(len(L) + 1)]
        yield L
        
# 直到评论区的凶狠解答
def triangles():
    L = [1]
    yield L
    while True:
        L=[1]+[L[x]+L[x+1] for x in range(len(L)-1)]+[1]
        yield L

  • 1

Reply