Discuss / Python / 出错了求解答

出错了求解答

Topic source

世事逝时

#1 Created at ... [Delete] [Delete and Lock User]
    tuple = [1]
    yield tuple
    tuple.append(1)
    yield tuple
    while True:
        n = len(tuple)
        while n>1:
            tuple[n-1] = tuple[n-1]+tuple[n-2]
            n = n - 1
        tuple.append(1)
        yield tuple

有没有大神告诉我上面的代码出来的结果为什么不对?

我单步调试的时候每一次的t都是对的,但是每一次的result都不对。比如第三次,result是[[1, 2, 1], [1, 2, 1], [1, 2, 1]]

全部运行后result是

[[1, 9, 36, 84, 126, 126, 84, 36, 9, 1], 

[1, 9, 36, 84, 126, 126, 84, 36, 9, 1], 

[1, 9, 36, 84, 126, 126, 84, 36, 9, 1], 

[1, 9, 36, 84, 126, 126, 84, 36, 9, 1], 

[1, 9, 36, 84, 126, 126, 84, 36, 9, 1], 

[1, 9, 36, 84, 126, 126, 84, 36, 9, 1], 

[1, 9, 36, 84, 126, 126, 84, 36, 9, 1], 

[1, 9, 36, 84, 126, 126, 84, 36, 9, 1], 

[1, 9, 36, 84, 126, 126, 84, 36, 9, 1], 

[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]]

杰成张

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

朋友,你这个忽略了列表是可变对象,你执行tuple[n-1]=..操作 和 tuple.append()操作时,list中之前添加的tuple也会跟着改变!代码可以改为如下:

def triangles():    tuple = [1]    yield tuple    tuple = [1,1]    yield tuple    while True:        n = len(tuple)        while n > 1:            tuple = tuple+[]            tuple[n - 1] = tuple[n - 1] + tuple[n - 2]            n = n - 1        tuple = tuple+[1]        yield tuple

  • 1

Reply