|
| 1 | +""" |
| 2 | + This module uses Python 3.8's a new feature |
| 3 | + 'math.comb' |
| 4 | + to calculate Pascal Triangle (https://en.wikipedia.org/wiki/Pascal%27s_triangle) |
| 5 | + and prints it into standard output |
| 6 | + e.g. |
| 7 | + 1 |
| 8 | + 1 1 |
| 9 | + 1 2 1 |
| 10 | + 1 3 3 1 |
| 11 | + 1 4 6 4 1 |
| 12 | + 1 5 10 10 5 1 |
| 13 | + 1 6 15 20 15 6 1 |
| 14 | + 1 7 21 35 35 21 7 1 |
| 15 | + 1 8 28 56 70 56 28 8 1 |
| 16 | + 1 9 36 84 126 126 84 36 9 1 |
| 17 | +
|
| 18 | +""" |
| 19 | + |
| 20 | +import math |
| 21 | +import sys |
| 22 | +import logging |
| 23 | + |
| 24 | + |
| 25 | +def bin_expans(row, col): |
| 26 | + """ |
| 27 | + Calculate binomial coefficient |
| 28 | + """ |
| 29 | + nCr = math.comb(row, col) |
| 30 | + return nCr |
| 31 | + |
| 32 | + |
| 33 | +def build_triangle(rows = 10): |
| 34 | + """ |
| 35 | + Calculate triangle |
| 36 | + """ |
| 37 | + triangle = [[str(bin_expans(row, col)) |
| 38 | + for col in range(row+1)] |
| 39 | + for row in range(rows)] |
| 40 | + return triangle |
| 41 | + |
| 42 | + |
| 43 | +def print_nicely(pascal_triangle): |
| 44 | + """ |
| 45 | + Print a Pascal Triangle |
| 46 | + iterable of iterables i.e. line and col |
| 47 | + """ |
| 48 | + for _row in pascal_triangle: |
| 49 | + str_row = " ".join(_row) |
| 50 | + last_row_len = len(" ".join(pascal_triangle[len(pascal_triangle)-1])) |
| 51 | + print(str_row.center(last_row_len, ' ')) |
| 52 | + |
| 53 | + |
| 54 | +if __name__ == "__main__": |
| 55 | + |
| 56 | + # Extract Python version info |
| 57 | + ver_major, ver_minor, _, _, _ = sys.version_info |
| 58 | + |
| 59 | + # Check if version is correct: should be above 3.8 |
| 60 | + if (ver_major*10 + ver_minor) < 38: |
| 61 | + logger = logging.getLogger(__name__) |
| 62 | + logging.warning("**** Python version must be above or equal to 3.8 for this module to work " |
| 63 | + "as it uses a new math's modules Combinatorial (math.comb) API ****") |
| 64 | + exit() |
| 65 | + |
| 66 | + # Check if a line argument is supplied and is valid |
| 67 | + no_of_rows = sys.argv[1] if len(sys.argv) > 1 and sys.argv[1].isdigit() else 10 |
| 68 | + |
| 69 | + # Build and print |
| 70 | + pascal_triangle = build_triangle(int(no_of_rows)) |
| 71 | + print_nicely(pascal_triangle) |
| 72 | + |
| 73 | + |
0 commit comments