130 likes | 267 Views
Recursion. Math Review. Given the following sequence: a 1 = 1 a n = 2*a n-1 OR a n+1 = 2*a n What are the values of the following? a 2 = a 3 = a 4 =. circular definition a function call within its own definition “using a function inside itself” Example: a(1) = 1
E N D
Math Review Given the following sequence: a1 = 1 an = 2*an-1 OR an+1 = 2*an What are the values of the following? a2 = a3 = a4 =
circular definition a function call within its own definition “using a function inside itself” Example: a(1) = 1 a(n) = 2*a(n-1) def a(n): if n == 1: return 1 return 2*a(n-1) What is recursion?
The Base Case • Every recursive algorithm has a starting/ending base case • What was the base case for the previous example? • What would happen if we did not have the base case?
Example • What is the base case and equation for the following sequence? a0 = 1 a1 = 1 a2 = 2 a3 = 6 a4 = 24 a5 = 120 a6 = 720
Recursive Function Construction • Always start with checking the base case • Recursively call (use) the function • Don’t forget to include any additional calculations
a0 = 1 an = n * an-1 OR a(0) = 1 a(n) = n * a(n-1) OR factorial(0) = 1 factorial(n) = n * factorial (n-1) def factorial(n): if n == 0: return 1 return n * factorial(n-1) Example
Tracing a Recursive Function def factorial(n): if n == 0: return 1 return n * factorial(n-1) print(factorial(4))
Your Turn • What is the base case and equation for the following sequence? a0 = 1 a1 = 1 a2 = 2 a3 = 3 a4 = 5 a5 = 8 a6 = 13
Your Turn • Implement the recursive function for the fibonacci sequence
Fibonacci def fib(n): if n == 0: return 1 if n == 1: return 1 return fib(n-1) + fib(n-2)
Recursion Advantages • Elegant solutions • Often fewer variables and fewer lines of code (LOCs) • Some problems are best solved using recursion (e.g. factorial, fibonacci)
Recursion Disadvantages • Recursive overhead slower than iteration • Tricky to follow • Recursion is not often actually implemented in practical code • Anything recursive can also be done with an iterative loop (and vice versa)