Discuss / Python / 一种用队列实现打印杨辉三角形的方法

一种用队列实现打印杨辉三角形的方法

Topic source

看了前边@kkopite 神奇的带列表生成式的答案,令人大开眼界。 实在是巧妙,凭本屌的水平是万万也想不出的。 这里献上一个队列实现打印杨辉三角形的笨拙写法。

def triangle():
      L=[0,1,0]
      while True:
          yield L[1:-1]
          for i in range(len(L)-1):
              L.append(L.pop(0)+L[0]) #弹出队首元素并将其与当前队首元素之和加入到队尾
          L.append(0) #加个0,帮队列推一下屁股,凑成标准体位。
In [655]: n=0

In [656]: for  t in triangle():
     ...:     print(t)
     ...:     n=n+1
     ...:     if n == 10:
     ...:         break
     ...:
[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]

LSJOP

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

我连最笨拙的方法也想不出来啊

LSJOP

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

没看明白这个i起什么作用

for i in range(len(L)-1):

W氵告Y

#4 Created at ... [Delete] [Delete and Lock User]
    L=[1]
    yield L
    L.append(1)
    yield L
    while True:
        L1=L[:]
        L.append(1)
        i=1
        while i<=len(L)-2:
            L[i]=L1[i-1]+L1[i]
            i=i+1
        yield L

  • 1

Reply