欢迎使用CSDN-markdown编辑器
2016-01-02 21:20
746 查看
Python编写杨辉三角
本文将介绍两种方法打印杨辉三角,一种使用通用的方法,一种使用Python生成器方法。方法1:通用方法
代码块语法遵循标准markdown代码,例如:def factor(n):
”’
循环求阶乘
”’
sum = 1
index = 1
if n == 0: return 1 while index <= n: sum *= index; index += 1 return sum
def factorial(n, k):
”’
求Cnk
”’
return factor(n) // (factor(k) * factor(n - k))
def pascalTriangle(line):
”’
:param line:杨辉三角的行数
:return:None
”’
outIndex = 0 inIndex = 0 while outIndex <= line - 1: #计算空格 while inIndex <= line - 1 - outIndex: print(" ", end="") inIndex += 1 #计算数值 inIndex = 0 while inIndex <= outIndex: print(factorial(outIndex, inIndex), end=" ") inIndex += 1 outIndex += 1 inIndex = 0 #打印换行 print("\n")
方法2:生成器方法
def pascalTriangle_generator(line):”’
:param line:杨辉三角的行数
:return:None
”’
pascalLine = [] outIndex = 0 inIndex = 0 while outIndex <= line - 1: #计算空格 while inIndex <= line - 1 - outIndex: pascalLine.append(" ") inIndex += 1 #计算数值 inIndex = 0 while inIndex <= outIndex: pascalLine.extend([factorial(outIndex, inIndex), " "]) inIndex += 1 outIndex += 1 inIndex = 0 #打印换行 yield pascalLine pascalLine = []
for line in pascalTriangle_generator(6):
index = 0
while index < len(line):
if len(str(line[index])):
print(line[index], end=”“)
print(” “, end=”“)
index += 1
print(“\n”)
两种方法使用相同的求组合数值算法。
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法