Discuss / Python / 请看这里:不需要写入参数,直接一个while True即可,利用下一个列表和当前列表的关系写出递推表达式

请看这里:不需要写入参数,直接一个while True即可,利用下一个列表和当前列表的关系写出递推表达式

Topic source

林宇璇Lynn

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

列表1 = [1]

列表2 = [1, 1]

然后开始递推迭代

1. 下一个列表首尾元素 = 当前列表的首尾元素

2. 下一个列表总长度 = 当前列表长度+1

3. 下一个列表中,除首尾外的中间元素,索引为i,会等于当前列表的第i-1个和第i个元素的和,lsn[i] = lsc[i-1] + lsc[i]

HERE  WE GO!

def triangles():

    ls1 = [1]

    ls2 = [1, 1]

    yield ls1

    yield ls2

    lsc = ls2 #当前列表从第二个列表开始递推到无穷

    while True:

        lsn = [] #下一个列表

        lsn.append(lsc[0]) #第一个元素为当前列表第一个元素

        n = len(lsc) + 1 #下一个列表的总长度

        for i in range(1, n-1): #中间元素们

            lsn.append(lsc[i-1]+lsc[i]) #递推关系

        lsn.append(lsc[-1]) #for 循环结束后填上最后一个元素

        yield lsn #yield 下一个列表

        lsc = lsn #将当前列表更新

dokyaes

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

逻辑好清晰,自己想的时候好混乱

Lee

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

#剽窃了大佬的思路写的

def y_s(n):  
    lsn=[1]
    lsc=[1,1]
    if n==1:
        yield lsn
    elif n==2:
        yield lsc
    else:
        i=2
        yield lsn
        yield lsc
        while i<=n:
            lsn=[]
            i=i+1
            lsn.append(1)
            for x in range(1,i-1):
                lsn.append(lsc[x-1]+lsc[x])
            lsn.append(1)
            yield lsn
            lsc=lsn       
for n in y_s(5): 
    print(n)


  • 1

Reply