forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfactorial.py
27 lines (20 loc) · 585 Bytes
/
factorial.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# Factorial of a number using memoization
fromfunctoolsimportlru_cache
@lru_cache
deffactorial(num: int) ->int:
"""
>>> factorial(7)
5040
>>> factorial(-1)
Traceback (most recent call last):
...
ValueError: Number should not be negative.
>>> [factorial(i) for i in range(10)]
[1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
"""
ifnum<0:
raiseValueError("Number should not be negative.")
return1ifnumin (0, 1) elsenum*factorial(num-1)
if__name__=="__main__":
importdoctest
doctest.testmod()