您的位置:首页 > 编程语言 > Python开发

欢迎使用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”)

两种方法使用相同的求组合数值算法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息