1 / 13

Recursion

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

Download Presentation

Recursion

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Recursion

  2. 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 =

  3. 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?

  4. 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?

  5. 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

  6. Recursive Function Construction • Always start with checking the base case • Recursively call (use) the function • Don’t forget to include any additional calculations

  7. 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

  8. Tracing a Recursive Function def factorial(n): if n == 0: return 1 return n * factorial(n-1) print(factorial(4))

  9. 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

  10. Your Turn • Implement the recursive function for the fibonacci sequence

  11. Fibonacci def fib(n): if n == 0: return 1 if n == 1: return 1 return fib(n-1) + fib(n-2)

  12. Recursion Advantages • Elegant solutions • Often fewer variables and fewer lines of code (LOCs) • Some problems are best solved using recursion (e.g. factorial, fibonacci)

  13. 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)

More Related