在 Python 中正确打印 Pascal 三角形

Print Pascal's Triangle in Python properly

我已经在 Python 中编写了 Pascal 三角程序,但该三角形打印为直角三角形

n=int(input("Enter the no. of rows: "))
for line in range(1, n + 1):  
    c = 1   
    x=n 
    y=line  

    for i in range(1, line + 1): 
    
        print(c, end = " ")
        c = int(c * (line - i) / i)
    print(" ")  

这给出了输出

Enter the no. of rows: 5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

但我想要它 this

n=int(input("Enter number of rows: "))
a=[]
for i in range(n):
    a.append([])
    a[i].append(1)
    for j in range(1,i):
        a[i].append(a[i-1][j-1]+a[i-1][j])
    if(n!=0):
        a[i].append(1)
for i in range(n):
    print("   "*(n-i),end=" ",sep=" ")   
    for j in range(0,i+1):
        print('{0:6}'.format(a[i][j]),end=" ",sep=" ")
    print()

print(" "*(n-i),end=" ",sep=" ") 行给出了您要查找的初始空格。

与其使用固定数字宽度,不如尝试让三角形自动调整:

rows = int(input("Enter the no. of rows: "))

triangle = []

for row in range(1, rows + 1):
    c = 1

    numbers = []

    for i in range(1, row + 1):
        numbers.append(c)
        c = c * (row - i) // i

    triangle.append(numbers)

last_row = triangle[-1]
number_width = len(str(max(last_row))) + 1
triangle_width = number_width * len(last_row)

for row in triangle:
    string = ""

    for number in row:
        number_string = str(number)
        string += number_string + ' ' * (number_width - len(number_string))

    print(string.center(triangle_width))

并利用 str.center() 方法!根据需要调整间距。

输出

> python3 test.py
Enter the no. of rows: 10
                  1                     
                1   1                   
              1   2   1                 
            1   3   3   1               
          1   4   6   4   1             
        1   5   10  10  5   1           
      1   6   15  20  15  6   1         
    1   7   21  35  35  21  7   1       
  1   8   28  56  70  56  28  8   1     
1   9   36  84  126 126 84  36  9   1   
> 

您可以简单地修改现有代码并进行 2 处修改 -

  1. 在每行前添加(n-line) spaces
  2. 将每个 1 位或 2 位数字居中对齐到 4 个字母表中 space(更改此设置会产生有趣的偏斜结果 :))
n=8
for line in range(1, n + 1):  
    c = 1   
    x=n
    y=line
    #######
    print("  "*(n-line), end="") #This line adds spaces before each line
    #######
    for i in range(1, line + 1): 
        ########
        print(str(c).center(4), end = "") #This center aligns each digit
        ########
        c = int(c * (line - i) / i)
    print(" ")  

               1   
             1   1   
           1   2   1   
         1   3   3   1   
       1   4   6   4   1   
     1   5   10  10  5   1   
   1   6   15  20  15  6   1   
 1   7   21  35  35  21  7   1