python3.x 语法的含义
the meaning of python3.x syntax
我想从 python 脚本制作一个帕斯卡三角形。这是我从 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)
问题是,这个脚本代码中的每一行都没有解释。所以谁能解释一下这个语法的每一行意思。
第一个函数pascal
生成一个存储在tri
中的帕斯卡三角形。 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
) 居中打印每行。
我想从 python 脚本制作一个帕斯卡三角形。这是我从 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)
问题是,这个脚本代码中的每一行都没有解释。所以谁能解释一下这个语法的每一行意思。
第一个函数pascal
生成一个存储在tri
中的帕斯卡三角形。 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
) 居中打印每行。