Skip to content
scipython.com

P2.5.1Pascal's triangle #2

Modify your solution to Problem 2.4.4 to output the first 50 rows of Pascal's triangle, but instead of the numbers themselves, output an asterisk if the number is odd and a space if it is even.

Show solution

The code below outputs the required pattern, which is a Sierpinski gasket.

# Output a pattern based on the parity of numbers in Pascal's Triangle

nmax = 50
rows = [[1],[1,1]]
for n in range(2, nmax+1):
    rows.append([1,])
    # Insert the entries for this row by summing neighbours in the previous row
    for k in range(n-1):
        rows[n].append(rows[n-1][k]+rows[n-1][k+1])
    rows[n].append(1)

# Pretty-print the rows as asterisks for odd numbers or else spaces
for i,row in enumerate(rows):
    s_row = []
    for x in row:
        if x % 2:
            s_row.append('*')
        else:
            s_row.append(' ')
    print(''.join(s_row))

The output is:

*
**
* *
****
*   *
**  **
* * * *
********
*       *
**      **
* *     * *
****    ****
*   *   *   *
**  **  **  **
* * * * * * * *
****************
...

The loop printing the asterisks can be expressed more concisely using list comprehension (Section 4.3.2):

for i,row in enumerate(rows):
    print(''.join(['*' if x % 2 else ' ' for x in row]))