Skip to content

Commit 5894554

Browse files
jrinder42github-actionspre-commit-ci[bot]
authored
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>
1 parent 660d2bb commit 5894554

File tree

2 files changed

+54
-1
lines changed

2 files changed

+54
-1
lines changed

Diff for: DIRECTORY.md

+3-1
Original file line numberDiff line numberDiff line change
@@ -475,6 +475,7 @@
475475
* [Binomial Coefficient](maths/binomial_coefficient.py)
476476
* [Binomial Distribution](maths/binomial_distribution.py)
477477
* [Bisection](maths/bisection.py)
478+
* [Catalan Number](maths/catalan_number.py)
478479
* [Ceil](maths/ceil.py)
479480
* [Check Polygon](maths/check_polygon.py)
480481
* [Chudnovsky Algorithm](maths/chudnovsky_algorithm.py)
@@ -632,8 +633,9 @@
632633

633634
## Physics
634635
* [Horizontal Projectile Motion](physics/horizontal_projectile_motion.py)
635-
* [Lorenz Transformation Four Vector](physics/lorenz_transformation_four_vector.py)
636+
* [Lorentz Transformation Four Vector](physics/lorentz_transformation_four_vector.py)
636637
* [N Body Simulation](physics/n_body_simulation.py)
638+
* [Newtons Law Of Gravitation](physics/newtons_law_of_gravitation.py)
637639
* [Newtons Second Law Of Motion](physics/newtons_second_law_of_motion.py)
638640

639641
## Project Euler

Diff for: maths/catalan_number.py

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
"""
2+
3+
Calculate the nth Catalan number
4+
5+
Source:
6+
https://en.wikipedia.org/wiki/Catalan_number
7+
8+
"""
9+
10+
11+
def catalan(number: int) -> int:
12+
"""
13+
:param number: nth catalan number to calculate
14+
:return: the nth catalan number
15+
Note: A catalan number is only defined for positive integers
16+
17+
>>> catalan(5)
18+
14
19+
>>> catalan(0)
20+
Traceback (most recent call last):
21+
...
22+
ValueError: Input value of [number=0] must be > 0
23+
>>> catalan(-1)
24+
Traceback (most recent call last):
25+
...
26+
ValueError: Input value of [number=-1] must be > 0
27+
>>> catalan(5.0)
28+
Traceback (most recent call last):
29+
...
30+
TypeError: Input value of [number=5.0] must be an integer
31+
"""
32+
33+
if not isinstance(number, int):
34+
raise TypeError(f"Input value of [number={number}] must be an integer")
35+
36+
if number < 1:
37+
raise ValueError(f"Input value of [number={number}] must be > 0")
38+
39+
current_number = 1
40+
41+
for i in range(1, number):
42+
current_number *= 4 * i - 2
43+
current_number //= i + 1
44+
45+
return current_number
46+
47+
48+
if __name__ == "__main__":
49+
import doctest
50+
51+
doctest.testmod()

0 commit comments

Comments
 (0)