From 5894554d41116af83152b1ea59fbf78303d87966 Mon Sep 17 00:00:00 2001 From: Jordan Rinder Date: Sat, 8 Oct 2022 18:28:17 -0400 Subject: [PATCH] Add Catalan number to maths (#6845) * Add Catalan number to maths * updating DIRECTORY.md * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- DIRECTORY.md | 4 +++- maths/catalan_number.py | 51 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 maths/catalan_number.py diff --git a/DIRECTORY.md b/DIRECTORY.md index 64e9d5333..668da4761 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -475,6 +475,7 @@ * [Binomial Coefficient](maths/binomial_coefficient.py) * [Binomial Distribution](maths/binomial_distribution.py) * [Bisection](maths/bisection.py) + * [Catalan Number](maths/catalan_number.py) * [Ceil](maths/ceil.py) * [Check Polygon](maths/check_polygon.py) * [Chudnovsky Algorithm](maths/chudnovsky_algorithm.py) @@ -632,8 +633,9 @@ ## Physics * [Horizontal Projectile Motion](physics/horizontal_projectile_motion.py) - * [Lorenz Transformation Four Vector](physics/lorenz_transformation_four_vector.py) + * [Lorentz Transformation Four Vector](physics/lorentz_transformation_four_vector.py) * [N Body Simulation](physics/n_body_simulation.py) + * [Newtons Law Of Gravitation](physics/newtons_law_of_gravitation.py) * [Newtons Second Law Of Motion](physics/newtons_second_law_of_motion.py) ## Project Euler diff --git a/maths/catalan_number.py b/maths/catalan_number.py new file mode 100644 index 000000000..4a1280a45 --- /dev/null +++ b/maths/catalan_number.py @@ -0,0 +1,51 @@ +""" + +Calculate the nth Catalan number + +Source: + https://en.wikipedia.org/wiki/Catalan_number + +""" + + +def catalan(number: int) -> int: + """ + :param number: nth catalan number to calculate + :return: the nth catalan number + Note: A catalan number is only defined for positive integers + + >>> catalan(5) + 14 + >>> catalan(0) + Traceback (most recent call last): + ... + ValueError: Input value of [number=0] must be > 0 + >>> catalan(-1) + Traceback (most recent call last): + ... + ValueError: Input value of [number=-1] must be > 0 + >>> catalan(5.0) + Traceback (most recent call last): + ... + TypeError: Input value of [number=5.0] must be an integer + """ + + if not isinstance(number, int): + raise TypeError(f"Input value of [number={number}] must be an integer") + + if number < 1: + raise ValueError(f"Input value of [number={number}] must be > 0") + + current_number = 1 + + for i in range(1, number): + current_number *= 4 * i - 2 + current_number //= i + 1 + + return current_number + + +if __name__ == "__main__": + import doctest + + doctest.testmod()