帕斯卡三角形(Pascal's Triangle)是一个数学上的二维数组,其中每个数字是其上方两个数字之和。它的每一行代表二项式系数,广泛应用于组合数学、概率论等领域。
帕斯卡三角形主要有两种类型:
以下是一个用Python实现的帕斯卡三角形二维数组格式化打印输出的示例代码:
def generate_pascals_triangle(num_rows):
triangle = []
for row_num in range(num_rows):
# The first and last row elements are always 1.
row = [None for _ in range(row_num + 1)]
row[0], row[-1] = 1, 1
# Each triangle element is equal to the sum of the elements above-and-to-the-left and above-and-to-the-right.
for j in range(1, len(row) - 1):
row[j] = triangle[row_num - 1][j - 1] + triangle[row_num - 1][j]
triangle.append(row)
return triangle
def print_pascals_triangle(triangle):
max_width = len(" ".join(map(str, triangle[-1])))
for row in triangle:
print(" ".join(map(str, row)).center(max_width))
# Generate and print Pascal's Triangle
num_rows = 10
triangle = generate_pascals_triangle(num_rows)
print_pascals_triangle(triangle)
print_pascals_triangle
函数中的对齐方式。通过以上方法,你可以生成并格式化打印帕斯卡三角形,适用于各种数学和编程应用场景。
领取专属 10元无门槛券
手把手带您无忧上云