Skip to content

update factorial #1535

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 31, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 28 additions & 15 deletions maths/factorial_python.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,34 @@
def factorial(input_number: int) -> int:
"""
Non-recursive algorithm of finding factorial of the
input number.
>>> factorial(1)
1
>>> factorial(6)
720
>>> factorial(0)
1
Calculate the factorial of specified number

>>> 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
"""

if input_number < 0:
raise ValueError("Input input_number should be non-negative")
elif input_number == 0:
return 1
else:
result = 1
for i in range(input_number):
result = result * (i + 1)
raise ValueError("factorial() not defined for negative values")
if not isinstance(input_number, int):
raise ValueError("factorial() only accepts integral values")
result = 1
for i in range(1, input_number):
result = result * (i + 1)
return result


if __name__ == '__main__':
import doctest

doctest.testmod()
36 changes: 26 additions & 10 deletions maths/factorial_recursive.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,30 @@
def fact(n):
def factorial(n: int) -> int:
"""
Return 1, if n is 1 or below,
otherwise, return n * fact(n-1).
Calculate the factorial of specified number

>>> 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__':
import doctest

"""
Show factorial for i,
where i ranges from 1 to 20.
"""
for i in range(1, 21):
print(i, ": ", fact(i), sep="")
doctest.testmod()