python基础练习--打印杨辉三角!

题目:打印杨辉三角

 

  1 # -*- coding:utf-8 -*-
  2 if __name__ == '__main__':
  3 #初始化三角
  4     a = []
  5     for i in range(10):
  6         a.append([])
  7         for j in range(10):
  8             a[i].append(0)
  9 #计算杨辉三角
 10     for i in range(10):
 11         a[i][0] = 1
 12         a[i][i] = 1
 13     for i in range(2,10):
 14         for j in range(1,i):
 15             a[i][j] = a[i-1][j-1] + a[i-1][j]
 16 #输出三角
 17     for i in range(10):
 18         for j in range(i+1):
 19             print a[i][j],
 20         print ''

结果:

 

 

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 

 

 

 

 

 

    原文作者:杨辉三角问题
    原文地址: https://blog.csdn.net/jerechen/article/details/79126463
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞