Skip to content

Instantly share code, notes, and snippets.

@jmw1040
Created November 15, 2017 20:02
Show Gist options
  • Save jmw1040/9adbeaee21976f2370e4f79b7a286f67 to your computer and use it in GitHub Desktop.
Save jmw1040/9adbeaee21976f2370e4f79b7a286f67 to your computer and use it in GitHub Desktop.
CMSC 121 - 14 - Recursion
### CMSC 12100
### Recursion
Consider the factorial.
This is an iterative solution:
def factorial_iterative(n):
rv = 1
for val in range(2, n+1):
rv = rv * val
return rv
For a recursive solution, we have a base case and a recursive case. The base case has input 1 and recursive case has input n
def factorial(n):
if n == 1:
return 1
elif n > 1:
return n * factorial(n-1)
####Permutations
Suppose we have a list $$[1, 2, 3]$$
The trivial case is either 1 element or 0 elements. But we'll stick with the base case of 1 element definition. Recursive case will be element 1, followed by permutations of remaining elements. And then element 2, followed by permutations of remaining. Etc.
def permutations(p):
if len(p) == 1:
return [p]
else:
rv = []
for val in p:
p_prime = [v for v in p if v!= x]
perms = permutations(p_prime)
for perm in perms:
pl = [x] + perm
rv.append(pl)
return rv
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment