# 用 Python 制作帕斯卡三角形

Lakshay Kapoor 2023年1月30日

## Python 中的帕斯卡三角算法

• 首先，从用户处获取输入数字以定义行数。
• 其次，定义一个空列表，用于存储值。
• 然后，使用 `for` 循环从 `0``n-1` 迭代，将子列表附加到初始列表。
• 之后，`1` 被附加到列表中。
• 然后，再次使用 `for` 循环将数字的值放入三角形的相邻行内。
• 最后，根据给定的格式打印帕斯卡三角形。

## 用 Python 编写帕斯卡三角形的程序

``````input_num = int(input("Enter the number of rows: "))
list = []  # an empty list
for n in range(input_num):
list.append([])
list[n].append(1)
for m in range(1, n):
list[n].append(list[n - 1][m - 1] + list[n - 1][m])
if input_num != 0:
list[n].append(1)
for n in range(input_num):
print(" " * (input_num - n), end=" ", sep=" ")
for m in range(0, n + 1):
print("{0:5}".format(list[n][m]), end=" ", sep=" ")
print()
``````

``````Enter the number: 5
1
1     1
1     2     1
1     3     3     1
1     4     6     4     1
``````

## 在 Python 中使用二项式系数打印帕斯卡三角形

``````num = int(input("Enter the number of rows:"))

for n in range(1, num + 1):
for m in range(0, num - n + 1):
print(" ", end="")

# first element is always 1
B = 1
for m in range(1, n + 1):

# first value in a line is always 1
print(" ", B, sep="", end="")

# using Binomial Coefficient
BC = B * (n - m) // m
print()
``````

``````Enter the number of rows:5
1
1 1
1 1 1
1 1 1 1
1 1 1 1 1
``````

``````BC = B(line(m), n-1) * (line(m) - n + 1) / n
``````

## 在 Python 中通过计算 `11` 的幂来打印帕斯卡的三角形

``````11 * 0 = 1
11 * 1 = 11
11 * 2 = 121
11 * 3 = 1331
11 * 4 = 14641
``````

``````num = int(input("Enter the number of rows:"))

for n in range(num):
print(" " * (num - n), end="")

print(" ".join(map(str, str(11 ** n))))
``````

``````Enter the number of rows:5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
``````

Lakshay Kapoor is a final year B.Tech Computer Science student at Amity University Noida. He is familiar with programming languages and their real-world applications (Python/R/C++). Deeply interested in the area of Data Sciences and Machine Learning.