Skip to content

Commit

Permalink
refactor(math): pascals triangle
Browse files Browse the repository at this point in the history
  • Loading branch information
BrianLusina committed Mar 14, 2024
1 parent cd82206 commit 20f7bf8
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 11 deletions.
15 changes: 14 additions & 1 deletion pymath/pascals_triangle/README.md
Original file line number Diff line number Diff line change
@@ -1 +1,14 @@
# Pascal's Triangle
# Pascal's Triangle

Given an index k, return the kth row of the Pascal's triangle.
Pascal's triangle: To generate A[C] in row R, sum up A'[C] and A'[C-1] from previous row R - 1.

```text
Example:
Input : k = 3
Return : [1,3,3,1]
```

Note: k is 0 based. k = 0, corresponds to the row [1].
21 changes: 11 additions & 10 deletions pymath/pascals_triangle/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from typing import List
from math import factorial as fac


Expand All @@ -8,30 +9,30 @@ def binomial(x, y):
return 0


def pascals_triangle(nth: int) -> list:
def pascals_triangle(nth: int) -> List[List[int]]:
"""
Generate Pascal's triangle of binomial coefficients upto the nth row
:param nth: Nth row to generate Pascal's triangle
:return: returns list of lists of each row or binomial coefficients of Pascal's triangle
"""
result = []
result: List[List[int]] = []
for x in range(nth + 1):
result.append([binomial(x, y) for y in range(x + 1)])

return result


def pascal_nth_row(nth: int) -> list:
def pascal_nth_row(nth: int) -> List[int]:
"""
Get's Pascal's Triangle Nth row and returns it
This is much faster than calculating the whole triangle and then fetching by it's index.
Instead we use the formula
NCr = (NCr - 1 * (N - r + 1)) / r where 1 ≤ r ≤ N
as the nth row consists of the following sequence:
NC0, NC1, ......, NCN - 1, NCN
Gets Pascal's Triangle Nth row and returns it
This is much faster than calculating the whole triangle and then fetching by its index.
We instead use the formula:
NCr = (NCr - 1 * (N - r + 1)) / r where 1 ≤ r ≤ N
as the nth row consists of the following sequence:
NC0, NC1, ......, NCN - 1, NCN
"""
ncr_1 = 1
row = [ncr_1]
row: List[int] = [ncr_1]

for i in range(1, nth + 1):
ncr = (ncr_1 * (nth - i + 1)) // i
Expand Down
15 changes: 15 additions & 0 deletions pymath/pascals_triangle/test_pascals_triangle.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import unittest
from . import pascals_triangle, pascal_nth_row


class PascalsTriangleTestCase(unittest.TestCase):
def test_1(self):
"""k=3 should return [1, 3, 3, 1]"""
k = 3
expected = [1, 3, 3, 1]
actual = pascal_nth_row(k)
self.assertEqual(expected, actual)


if __name__ == '__main__':
unittest.main()

0 comments on commit 20f7bf8

Please sign in to comment.