File tree 2 files changed +54
-25
lines changed
2 files changed +54
-25
lines changed Original file line number Diff line number Diff line change 1
1
def factorial (input_number : int ) -> int :
2
2
"""
3
- Non-recursive algorithm of finding factorial of the
4
- input number.
5
- >>> factorial(1)
6
- 1
7
- >>> factorial(6)
8
- 720
9
- >>> factorial(0)
10
- 1
3
+ Calculate the factorial of specified number
4
+
5
+ >>> factorial(1)
6
+ 1
7
+ >>> factorial(6)
8
+ 720
9
+ >>> factorial(0)
10
+ 1
11
+ >>> factorial(-1)
12
+ Traceback (most recent call last):
13
+ ...
14
+ ValueError: factorial() not defined for negative values
15
+ >>> factorial(0.1)
16
+ Traceback (most recent call last):
17
+ ...
18
+ ValueError: factorial() only accepts integral values
11
19
"""
12
20
13
21
if input_number < 0 :
14
- raise ValueError ("Input input_number should be non-negative" )
15
- elif input_number == 0 :
16
- return 1
17
- else :
18
- result = 1
19
- for i in range (input_number ):
20
- result = result * (i + 1 )
22
+ raise ValueError ("factorial() not defined for negative values" )
23
+ if not isinstance (input_number , int ):
24
+ raise ValueError ("factorial() only accepts integral values" )
25
+ result = 1
26
+ for i in range (1 , input_number ):
27
+ result = result * (i + 1 )
21
28
return result
29
+
30
+
31
+ if __name__ == '__main__' :
32
+ import doctest
33
+
34
+ doctest .testmod ()
Original file line number Diff line number Diff line change 1
- def fact ( n ) :
1
+ def factorial ( n : int ) -> int :
2
2
"""
3
- Return 1, if n is 1 or below,
4
- otherwise, return n * fact(n-1).
3
+ Calculate the factorial of specified number
4
+
5
+ >>> factorial(1)
6
+ 1
7
+ >>> factorial(6)
8
+ 720
9
+ >>> factorial(0)
10
+ 1
11
+ >>> factorial(-1)
12
+ Traceback (most recent call last):
13
+ ...
14
+ ValueError: factorial() not defined for negative values
15
+ >>> factorial(0.1)
16
+ Traceback (most recent call last):
17
+ ...
18
+ ValueError: factorial() only accepts integral values
5
19
"""
6
- return 1 if n <= 1 else n * fact (n - 1 )
20
+ if n < 0 :
21
+ raise ValueError ("factorial() not defined for negative values" )
22
+ if not isinstance (n , int ):
23
+ raise ValueError ("factorial() only accepts integral values" )
24
+ return 1 if n == 0 or n == 1 else n * factorial (n - 1 )
25
+
7
26
27
+ if __name__ == '__main__' :
28
+ import doctest
8
29
9
- """
10
- Show factorial for i,
11
- where i ranges from 1 to 20.
12
- """
13
- for i in range (1 , 21 ):
14
- print (i , ": " , fact (i ), sep = "" )
30
+ doctest .testmod ()
You can’t perform that action at this time.
0 commit comments