Discuss / Python / qwq来康康嘛

qwq来康康嘛

Topic source

520bv

#1 Created at ... [Delete] [Delete and Lock User]
# -*- coding: utf-8 -*-def triangles():
    m = [1]
    n = 1
    while 1:
        yield m
        n += 1
        if n == 2:
            m = [1, 1]   #此处若是:  m.append(1) 则测试失败
        else:
            m = [m[x] + m[x + 1] for x in range(n) if x < n - 2]
            m.insert(0, 1)
            m.append(1)
    return 'Done'
# 期待输出:
# [1]
# [1, 1
]# [1, 2, 1
]# [1, 3, 3, 1]
# [1, 4, 6, 4, 1]
# [1, 5, 10, 10, 5, 1]
# [1, 6, 15, 20, 15, 6, 1]
# [1, 7, 21, 35, 35, 21, 7, 1]
# [1, 8, 28, 56, 70, 56, 28, 8, 1]
# [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]n = 0results = []
for t in triangles():
    results.append(t)
    n = n + 1
    if n == 10:
        breakfor t in results:
    print(t)

if results == 
[
    [1],
    [1, 1],
    [1, 2, 1],
    [1, 3, 3, 1],
    [1, 4, 6, 4, 1],
    [1, 5, 10, 10, 5, 1],
    [1, 6, 15, 20, 15, 6, 1],
    [1, 7, 21, 35, 35, 21, 7, 1],
    [1, 8, 28, 56, 70, 56, 28, 8, 1],
    [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
]:
    print('测试通过!')
else:
    print('测试失败!')

问题如代码,

            m = [1, 1]   #此处若是:  m.append(1) 则测试失败

我一步步debug过,发现当生成器函数中n=2时,执行m.append(1)

发现原来的第一个列表[1]→[1, 1],第二个后面的毫无问题

我就想了想list.append(index,obj)方法是在原列表末尾添加就是说在原列表基础上做的

而直接用m = [1, 1]相当于:

m = [1]            #原来的m
t = [1, 1]         #定义一个t列表
m = t              #把m变量指向t列表,原来那个列表就不再是m指向了

下面else中的表达式也是同理

我就想问下,除了我这种改法,有木有别的办法解决?

本人小白一枚,球球大L们指点


  • 1

Reply