Discuss / Python / 不懂就问

不懂就问

Topic source

路遥无马

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

评论区的大家的方法调用next()返回始终为[1];方法一的问题for t in triangles():   print(t)打印出来的结果是正常的,但页面的测试会失败;方法二都正常,本质区别是什么。

方法一:

def triangles():

    a=[1]

    while True:

        yield a

        a.append(1)

        b = a[:]

        for n in range(len(a)-2):

            a[n+1] = b[n] + b[n+1]

方法二

def triangles():

    a = [1]

    b = [1]

    while True:

        yield a

        b.append(1)

        for n in range(len(a)-1):

            b[n+1] = a[n] + a[n+1]

        a = b[:]

Laniakea-cly

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

def tri():

    a = [1]

    while 1:

        yield a

        a.append(1)

        b = a[:]

        for n in range(len(a)-2):

            a[n+1] = b[n] + b[n+1]

n = 0

results = []

for t in tri():

    results.append(t)

    print(t)

    print(results)

    n = n + 1

    if n == 3:

        break

以下是我的结果,请问这是为什么??

[1]
[[1]]
[1, 1]
[[1, 1], [1, 1]]
[1, 2, 1]
[[1, 2, 1], [1, 2, 1], [1, 2, 1]]

  • 1

Reply