mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-23 21:11:08 +00:00
4b79d771cd
* Add more ruff rules * Add more ruff rules * pre-commit: Update ruff v0.0.269 -> v0.0.270 * Apply suggestions from code review * Fix doctest * Fix doctest (ignore whitespace) * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: Dhruv Manilawala <dhruvmanila@gmail.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
54 lines
1.2 KiB
Python
54 lines
1.2 KiB
Python
"""
|
|
|
|
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):
|
|
msg = f"Input value of [number={number}] must be an integer"
|
|
raise TypeError(msg)
|
|
|
|
if number < 1:
|
|
msg = f"Input value of [number={number}] must be > 0"
|
|
raise ValueError(msg)
|
|
|
|
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()
|