Creative Commons License
This work is licensed under a Creative Commons Attribution 3.0 Unported License.

Sunday, May 5, 2013

Nested loop: Pascal triangle using Binomial Coefficients


Problem: Print Pascal's triangle using Binomial Coefficients.

Example: n = 6

                  1 
                1    1 
             1    2    1 
           1    3    3    1 
        1    4    6    4    1 
     1    5   10   10    5    1 

Hint: Row number r, has all of its binomial coefficients, e.g. r=3 (row 4), has C(3,0), C(3,1), C(3,2), C(3,3)

Solution in Python:


from __future__ import division

import math

def pascal_triangle(n):
    """
    Author: Mayur P Srivastava
    """

    for r in range(n):
        row = []
        for i in range(r+1):
            row.append(0)

        for k in range(int(math.ceil((r+1)/2))):
            row[k] = row[r-k] = int(binomial_coefficient(r, k))

        print format_row(row, r+1, n)


def binomial_coefficient(r, k):
    p = 1
    for j in range(1, k+1):
        p *= (r+1-j) / j
    return p


def format_row(row, row_number, n, max_element_len=4):
    offset = int(math.floor((n - row_number) / 2))

    element_pattern = "%%%ds " % max_element_len

    row_str = ""
    for i in range(offset+1):
        row_str += element_pattern % ""

    for element in row:
        row_str += element_pattern % element

    return row_str

Concepts learned: Nested loops.

No comments:

Post a Comment