-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecursion.py
More file actions
49 lines (37 loc) · 1.35 KB
/
recursion.py
File metadata and controls
49 lines (37 loc) · 1.35 KB
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#!python
def factorial(n):
"""factorial(n) returns the product of the integers 1 through n for n >= 0,
otherwise raises ValueError for n < 0 or non-integer n"""
# check if n is negative or not an integer (invalid input)
if not isinstance(n, int) or n < 0:
raise ValueError('factorial is undefined for n = {}'.format(n))
# implement factorial_iterative and factorial_recursive below, then
# change this to call your implementation to verify it passes all tests
# return factorial_iterative(n)
return factorial_recursive(n)
def factorial_iterative(n):
factorial = 1
# Could start at range 2 because the nature of factorials both 1! and 0!
# are 1
for count in range(1, n + 1):
factorial *= count
return factorial
def factorial_recursive(n):
# check if n is one of the base cases
if n == 0 or n == 1:
return 1
# check if n is an integer larger than the base cases
elif n > 1:
# Recursive call
return n * factorial_recursive(n - 1)
def main():
import sys
args = sys.argv[1:] # Ignore script file name
if len(args) == 1:
num = int(args[0])
result = factorial(num)
print('factorial({}) => {}'.format(num, result))
else:
print('Usage: {} number'.format(sys.argv[0]))
if __name__ == '__main__':
main()