Discuss / Python / 好吧我承认我蠢没有那些大神厉害 只能写成这样了

好吧我承认我蠢没有那些大神厉害 只能写成这样了

Topic source

正版琅琊

#1 Created at ... [Delete] [Delete and Lock User]

没有那些大神厉害 只能写成这样了

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def triangles():
    temp=[1]
    tempold=temp[:]
    yield temp
    ci=2
    i=1
    while i<=ci:
        if i==1:
            temp=[]
            temp.insert(i-1,1)
            i=i+1
        elif i==ci:
            temp.insert(i-1,1)
            tempold=temp[:]
            i=1
            ci=ci+1
            yield temp
        else:
            temp.append(tempold[i-2]+tempold[i-1])

            i=i+1

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

廖雪峰

#2 Created at ... [Delete] [Delete and Lock User]

你需要换个思路:

假设某一行的结果已经计算出来了,比如:[1, 4, 6, 4, 1]

怎么计算下一行呢?

把当前行首尾分别添加0,得到:

[0, 1, 4, 6, 4, 1]
[1, 4, 6, 4, 1, 0]

再把上面的两行按列对应相加,得到下一行结果:

[1, 5, 10, 10, 5, 1]

所以代码可以简化为:

def triangles():
    r = [1]
    while True:
        yield r
        # 根据当前行计算下一行:
        r = calculate_next(r)

  • 1

Reply