2019-10-31 12:45:32 +00:00
|
|
|
def factorial(n: int) -> int:
|
2019-07-02 04:05:43 +00:00
|
|
|
"""
|
2020-01-18 13:06:48 +00:00
|
|
|
Calculate the factorial of a positive integer
|
|
|
|
https://en.wikipedia.org/wiki/Factorial
|
2019-10-31 12:45:32 +00:00
|
|
|
|
2020-01-18 13:06:48 +00:00
|
|
|
>>> import math
|
|
|
|
>>> all(factorial(i) == math.factorial(i) for i in range(20))
|
|
|
|
True
|
2019-10-31 12:45:32 +00:00
|
|
|
>>> factorial(0.1)
|
|
|
|
Traceback (most recent call last):
|
|
|
|
...
|
|
|
|
ValueError: factorial() only accepts integral values
|
2020-01-18 13:06:48 +00:00
|
|
|
>>> factorial(-1)
|
|
|
|
Traceback (most recent call last):
|
|
|
|
...
|
|
|
|
ValueError: factorial() not defined for negative values
|
2019-07-02 04:05:43 +00:00
|
|
|
"""
|
2019-10-31 12:45:32 +00:00
|
|
|
if not isinstance(n, int):
|
|
|
|
raise ValueError("factorial() only accepts integral values")
|
2020-01-18 13:06:48 +00:00
|
|
|
if n < 0:
|
|
|
|
raise ValueError("factorial() not defined for negative values")
|
2019-10-31 12:45:32 +00:00
|
|
|
return 1 if n == 0 or n == 1 else n * factorial(n - 1)
|
|
|
|
|
2019-07-02 04:05:43 +00:00
|
|
|
|
2019-11-14 18:59:43 +00:00
|
|
|
if __name__ == "__main__":
|
2019-10-31 12:45:32 +00:00
|
|
|
import doctest
|
2019-04-22 14:53:56 +00:00
|
|
|
|
2019-10-31 12:45:32 +00:00
|
|
|
doctest.testmod()
|