DEV Community

loading...
Cover image for Day 16: Pascal's Pyramid

Day 16: Pascal's Pyramid

mattryanmtl profile image Matt Ryan ・1 min read

Pascal's Pyramid is the 3-dimensional version of Pascal's Triangle.
Alt Text

Like in Pascal's Triangle, each number is the sum of numbers above it. The cap of the pyramid (Row 0) is 1. In Row 1, the three numbers are 1, just as in the triangle, because it is the sum of numbers above it. Each number in the following rows is the sum of the numbers above it.
Alt Text

from functools import lru_cache

@lru_cache(maxsize=None)
def trinomial_coefficient(l, n, k):
    if l < 0 or n < 0 or k < 0:
        return 0

    head = (n == 0 and k == 0)
    bottom_left = (n == l) and (k == 0)
    bottom_right = (n == l) and (k == l)

    if head or bottom_left or bottom_right:
        return 1

    return (trinomial_coefficient(l-1, n-1, k-1) +
            trinomial_coefficient(l-1, n-1, k) +
            trinomial_coefficient(l-1, n, k))


def pascal_pyramid(l):
    rows = list()
    for n in range(l+1):
        coefficients = list()
        for k in range(n+1):
            coefficients.append(trinomial_coefficient(l, n, k))
        rows.append(coefficients)
    return rows

for row in pascal_pyramid(5-1):
    print(row)
Enter fullscreen mode Exit fullscreen mode

Discussion (0)

Forem Open with the Forem app