Discuss / Python / Macyrate

Macyrate

Topic source

Macyrate

#1 Created at ... [Delete] [Delete and Lock User]
# -*- coding: utf-8 -*-
def triangles():
    Last = [1]
    yield Last         #返回第一行
    while 1:
        L = [1]        #每行开头的1
        for x in range(1,len(Last)):
                L.append(Last[x-1]+Last[x])
                       #中间满足:L[x]=Last[x-1]+Last[x]
        L.append(1)    #每行最后的1
        Last = L[:]    #新生成的行在下次迭代时作为上一行
        yield L        #返回新生成的行

# 期待输出:
# [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 = 0
results = []
for t in triangles():
    print(t)
    results.append(t)
    n = n + 1
    if n == 10:
        break
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('测试失败!')

这里的 while 1 和 while true 是一个意思吗?

lowkeyjoe

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

在条件里0为false,非零为true

为什么?

for x in range(1,len(Last)):
        L.append(Last[x-1]+Last[x])

当len(Last)=1的时候,也就是即将打印第二列的时候,

L.append(Last[x-1]+Last[x])并没有添加数据进入L列表呢?

懂了


  • 1

Reply