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>
This commit is contained in:
Jordan Rinder 2022-10-08 18:28:17 -04:00 committed by GitHub
parent 660d2bb66c
commit 5894554d41
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 54 additions and 1 deletions

View File

@ -475,6 +475,7 @@
* [Binomial Coefficient](maths/binomial_coefficient.py) * [Binomial Coefficient](maths/binomial_coefficient.py)
* [Binomial Distribution](maths/binomial_distribution.py) * [Binomial Distribution](maths/binomial_distribution.py)
* [Bisection](maths/bisection.py) * [Bisection](maths/bisection.py)
* [Catalan Number](maths/catalan_number.py)
* [Ceil](maths/ceil.py) * [Ceil](maths/ceil.py)
* [Check Polygon](maths/check_polygon.py) * [Check Polygon](maths/check_polygon.py)
* [Chudnovsky Algorithm](maths/chudnovsky_algorithm.py) * [Chudnovsky Algorithm](maths/chudnovsky_algorithm.py)
@ -632,8 +633,9 @@
## Physics ## Physics
* [Horizontal Projectile Motion](physics/horizontal_projectile_motion.py) * [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) * [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) * [Newtons Second Law Of Motion](physics/newtons_second_law_of_motion.py)
## Project Euler ## Project Euler

51
maths/catalan_number.py Normal file
View File

@ -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()