diff --git a/DIRECTORY.md b/DIRECTORY.md index 24a948802f68..c50995721f50 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -1028,6 +1028,8 @@ * [Activity Selection](other/activity_selection.py) * [Alternative List Arrange](other/alternative_list_arrange.py) * [Bankers Algorithm](other/bankers_algorithm.py) + * [Cheap Progress](other/cheap_progress.py) + * [Dancing Links](other/dancing_links.py) * [Davis Putnam Logemann Loveland](other/davis_putnam_logemann_loveland.py) * [Doomsday](other/doomsday.py) * [Fischer Yates Shuffle](other/fischer_yates_shuffle.py) @@ -1051,6 +1053,7 @@ * [Scoring Algorithm](other/scoring_algorithm.py) * [Sdes](other/sdes.py) * [Sliding Window Maximum](other/sliding_window_maximum.py) + * [Token Bucket](other/token_bucket.py) * [Tower Of Hanoi](other/tower_of_hanoi.py) * [Word Search](other/word_search.py) diff --git a/maths/factorial.py b/maths/factorial.py index 2b8b68764d89..a04fd5887802 100644 --- a/maths/factorial.py +++ b/maths/factorial.py @@ -5,11 +5,17 @@ def factorial(number: int) -> int: """ - Calculate the factorial of specified number (n!). + Calculate the factorial of the specified number. >>> import math >>> all(factorial(i) == math.factorial(i) for i in range(20)) True + >>> factorial(0) + 1 + >>> factorial(1) + 1 + >>> factorial(5) + 120 >>> factorial(0.1) Traceback (most recent call last): ... @@ -18,12 +24,6 @@ def factorial(number: int) -> int: Traceback (most recent call last): ... ValueError: factorial() not defined for negative values - >>> factorial(1) - 1 - >>> factorial(6) - 720 - >>> factorial(0) - 1 """ if number != int(number): raise ValueError("factorial() only accepts integral values") @@ -35,14 +35,19 @@ def factorial(number: int) -> int: return value -def factorial_recursive(n: int) -> int: +def factorial_recursive(number: int) -> int: """ - Calculate the factorial of a positive integer - https://en.wikipedia.org/wiki/Factorial + Calculate the factorial of a number using recursion. >>> import math >>> all(factorial_recursive(i) == math.factorial(i) for i in range(20)) True + >>> factorial_recursive(0) + 1 + >>> factorial_recursive(1) + 1 + >>> factorial_recursive(5) + 120 >>> factorial_recursive(0.1) Traceback (most recent call last): ... @@ -52,17 +57,16 @@ def factorial_recursive(n: int) -> int: ... ValueError: factorial_recursive() not defined for negative values """ - if not isinstance(n, int): + if not isinstance(number, int): raise ValueError("factorial_recursive() only accepts integral values") - if n < 0: + if number < 0: raise ValueError("factorial_recursive() not defined for negative values") - return 1 if n in {0, 1} else n * factorial_recursive(n - 1) + return 1 if number in {0, 1} else number * factorial_recursive(number - 1) if __name__ == "__main__": import doctest doctest.testmod() - n = int(input("Enter a positive integer: ").strip() or 0) - print(f"factorial{n} is {factorial(n)}") + print(f"{n = } {factorial(n) = } {factorial_recursive(n) = }")