Discuss / Python / 生成器函数传入参数,打印10行传入10即可

生成器函数传入参数,打印10行传入10即可

Topic source
# 通过生成器来打印杨辉三角
def triangles(row_count):
    if row_count <= 0:
        return '行数必须大于0'
    rows = [[1], [1, 1]]
    temp = 0
    while temp < row_count:
        if temp > 1:
            current_row = []
            current_row.append(1)
            for n in range(temp - 1):
                current_row.append(rows[temp - 1][n] + rows[temp - 1][n + 1])
            current_row.append(1)
            rows.append(current_row)
        yield rows[temp]
        temp += 1


for t in triangles(10):
    print(t)

  • 1

Reply