forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add Catalan number to maths (TheAlgorithms#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>
- Loading branch information
1 parent
660d2bb
commit 5894554
Showing
2 changed files
with
54 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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() |