CMPT 120 Lecture 19 – Unit 3 – Graphics and Animation Python – Implementing and Visualizing Recursion
Review – What to consider when creating a function Function interface Function name (to reflect the task performed by the function) Parameter(s) Returned value
Review – What to consider when creating a recursive function Base Case Stops the function from calling itself indefinitely Recursive Case This is where the function calls itself with a modified (often smaller) form of the problem How do we get this “modified form of the problem” -> a rule
Last Lecture – we were here! Descriptive function name 1 parameter -> n Docstring describes the task performed by our function Let’s complete our program!
Execution Flow and Recursion How does recursion actually work? How can we test our recursive function? Let’s have a look at it through the Python Code Visualizer Online textbook calls this box tracing Box tracing technique used to hand trace the execution of a function (especially a recursive function) in order to figure out what it does
Box tracing a recursive function Knowing how to hand/box trace code is very important Even more important when dealing with recursive functions Why? Because following the execution of recursive functions can become very complicated very quickly Box tracing allows us to figure out what a recursive function does (keeping track of its parameters and local variables), what it produces (keeping track of its returned value) and where the execution flow returns to in a systematic way
Let’s try this again! Problem Statement Write a Python function that reverse a string
Let’s go back to our Turtle Trees! And have a look at more complicated recursive function that draws trees using a dictionary What does a dictionary have to do with trees?
Next Lecture Feedback on our algorithms of last Friday New practice exercises