Skip to content
scipython.com

P8.1.1Pascal's triangle

Use scipy.special.binom to create a depiction of Pascal's triangle of binomial coefficients \(\binom{n}{k}\) up to \(n=8\).

Show solution
pascalstriangle
import numpy as np
from scipy.special import binom

nmax = 8
for n in range(nmax + 1):
    fmt = " {:^3d}" * (n + 1)
    pascal_row = fmt.format(*np.array(binom(n, np.arange(n + 1)), dtype="i4"))
    print(f"{pascal_row:^40s}")

The \(n\)th row of Pascal's triangle contains \(n\) numbers, each of which is formatted in a field width of three characters; the entire row is then centered in a total field size of 40 characters.

Output:

                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