mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-02-07 10:00:55 +00:00
parent
80e1c8748a
commit
814750e637
|
@ -1,21 +1,34 @@
|
||||||
def factorial(input_number: int) -> int:
|
def factorial(input_number: int) -> int:
|
||||||
"""
|
"""
|
||||||
Non-recursive algorithm of finding factorial of the
|
Calculate the factorial of specified number
|
||||||
input number.
|
|
||||||
>>> factorial(1)
|
>>> factorial(1)
|
||||||
1
|
1
|
||||||
>>> factorial(6)
|
>>> factorial(6)
|
||||||
720
|
720
|
||||||
>>> factorial(0)
|
>>> factorial(0)
|
||||||
1
|
1
|
||||||
|
>>> factorial(-1)
|
||||||
|
Traceback (most recent call last):
|
||||||
|
...
|
||||||
|
ValueError: factorial() not defined for negative values
|
||||||
|
>>> factorial(0.1)
|
||||||
|
Traceback (most recent call last):
|
||||||
|
...
|
||||||
|
ValueError: factorial() only accepts integral values
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if input_number < 0:
|
if input_number < 0:
|
||||||
raise ValueError("Input input_number should be non-negative")
|
raise ValueError("factorial() not defined for negative values")
|
||||||
elif input_number == 0:
|
if not isinstance(input_number, int):
|
||||||
return 1
|
raise ValueError("factorial() only accepts integral values")
|
||||||
else:
|
result = 1
|
||||||
result = 1
|
for i in range(1, input_number):
|
||||||
for i in range(input_number):
|
result = result * (i + 1)
|
||||||
result = result * (i + 1)
|
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
import doctest
|
||||||
|
|
||||||
|
doctest.testmod()
|
||||||
|
|
|
@ -1,14 +1,30 @@
|
||||||
def fact(n):
|
def factorial(n: int) -> int:
|
||||||
"""
|
"""
|
||||||
Return 1, if n is 1 or below,
|
Calculate the factorial of specified number
|
||||||
otherwise, return n * fact(n-1).
|
|
||||||
|
>>> factorial(1)
|
||||||
|
1
|
||||||
|
>>> factorial(6)
|
||||||
|
720
|
||||||
|
>>> factorial(0)
|
||||||
|
1
|
||||||
|
>>> factorial(-1)
|
||||||
|
Traceback (most recent call last):
|
||||||
|
...
|
||||||
|
ValueError: factorial() not defined for negative values
|
||||||
|
>>> factorial(0.1)
|
||||||
|
Traceback (most recent call last):
|
||||||
|
...
|
||||||
|
ValueError: factorial() only accepts integral values
|
||||||
"""
|
"""
|
||||||
return 1 if n <= 1 else n * fact(n - 1)
|
if n < 0:
|
||||||
|
raise ValueError("factorial() not defined for negative values")
|
||||||
|
if not isinstance(n, int):
|
||||||
|
raise ValueError("factorial() only accepts integral values")
|
||||||
|
return 1 if n == 0 or n == 1 else n * factorial(n - 1)
|
||||||
|
|
||||||
|
|
||||||
"""
|
if __name__ == '__main__':
|
||||||
Show factorial for i,
|
import doctest
|
||||||
where i ranges from 1 to 20.
|
|
||||||
"""
|
doctest.testmod()
|
||||||
for i in range(1, 21):
|
|
||||||
print(i, ": ", fact(i), sep="")
|
|
||||||
|
|
Loading…
Reference in New Issue
Block a user