python杨辉三角
来源:互联网 发布:linux安装jdk1.7 64位 编辑:程序博客网 时间:2024/06/06 00:39
实现效果
[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]Process finished with exit code 0
代码
def triangles(n=10): L = [1] for i in range(n): yield L L=[L[0]] + [L[j]+L[j+1] for j in range(len(L)-1)] + [L[-1]]for data in triangles(): print(data)
说明
参看python生成器的相关内容,可知在for迭代过程中,yield处断点并输出list类型的L,建议可结合调试分析论证。
关于表达式:
L=[L[0]] + [L[j]+L[j+1] for j in range(len(L)-1)] + [L[-1]]
事实上,L[0]==L[-1]==1也就是杨辉三角每行的第一个元素和最后一个元素都是1,此处应该注意:对于list集合的添加,比如说:
print([1]+['fds'])
结果是:[1, ‘fds’],当然L[-1]必须放在表达式最后。
也就是说,我们可以简而言之:
[L[j]+L[j+1] for j in range(len(L)-1)]
这个list集合与列表生成式有关,即在上一个list集合(L)根据L[i+1]=L[i]+L[i+1]进行计算(按顺序两两结合,共原长-1),注意结果仍然是list集合。
0 0
- Python - 杨辉三角
- Python 杨辉三角
- python-杨辉三角
- python杨辉三角
- python杨辉三角
- 杨辉三角 Python
- Python-杨辉三角
- python实现杨辉三角
- 杨辉三角python实现
- python 打印杨辉三角
- python.杨辉三角.生成器
- Python打印杨辉三角
- python 打印杨辉三角
- python 编写杨辉三角
- python实现杨辉三角
- 杨辉三角 python实现
- python|打印杨辉三角
- python打印杨辉三角
- 关于删除数组中相同元素的一个小技巧
- effective javascript(七)——命名函数表达式
- C++作业4
- [LeetCode]263. Ugly Number
- intellij自动生成java代码注释(java文件注释和方法注释)
- python杨辉三角
- c sharp 菜鸟的学习历程3
- 在线购物系统实验二
- MyBatis中Insert操作介绍
- adb命令模拟按键事件 KeyCode
- Python-pip 安装失败问题解决
- [序言]写在前面
- 线程资源的回收
- 51Nod 1001 数组中和等于K的数对