我想从python脚本制作一个pascal三角形。这是我从web.programminghub.io
获得的语法size = int(input("Enter the size of the triangle: "))
tri=[]
#creates a pascal triangle of size n
def pascal(n):
"""Prints out n rows of Pascal's triangle.
It returns False for failure and True for success."""
row = [1]
k = [0]
for x in range(max(n,0)):
tri.append(row)
row=[l+r for l,r in zip(row+k,k+row)]
return n>=1
#prints the pascal triangle with correct spacing to
#represent a triangle
def print_pascals_triangle(triangle):
largest_element = triangle[-1][len(triangle[-1]) // 2]
element_width = len(str(largest_element))
def format_row(row):
return ' '.join([str(element).center(element_width)
for element in row])
triangle_width = len(format_row(triangle[-1]))
for row in triangle:
print(format_row(row).center(triangle_width))
pascal(size)
print_pascals_triangle(tri)
问题是,没有解释此脚本代码中的每一行。所以有人可以解释这种语法含义的每一行。
答案 0 :(得分:1)
第一个函数pascal
生成存储在tri
中的pascal三角形。 print_pascals_triangle
对称地打印三角形。
Enter the size of the triangle: 3
1
1 1
1 2 1
pascal
生成[[1], [1, 1], [1, 2, 1]]
。
print_pascals_triangle
打印以固定宽度(triangle_width
)为中心的每一行。