Lecture 6 - Recursion.

Slides:



Advertisements
Similar presentations
Designing Algorithms Csci 107 Lecture 3. Designing algorithms Last time –Pseudocode –Algorithm: computing the sum 1+2+…+n –Gauss formula for 1+2+…+n Today.
Advertisements

Complexity (Running Time)
CHAPTER 10 Recursion. 2 Recursive Thinking Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
CS212: DATASTRUCTURES Lecture 3: Recursion 1. Lecture Contents 2  The Concept of Recursion  Why recursion?  Factorial – A case study  Content of a.
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
M180: Data Structures & Algorithms in Java
Fall Week 3 CSCI-141 Scott C. Johnson.  Say we want to draw the following figure ◦ How would we go about doing this?
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 19 : Recursion King Fahd University of Petroleum & Minerals College of Computer.
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
CS212: DATASTRUCTURES Lecture 3: Recursion 1. Lecture Contents 2  The Concept of Recursion  Why recursion?  Factorial – A case study  Content of a.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
 Expression Tree and Objects 1. Elements of Python  Literals, Strings, Tuples, Lists, …  The order of file reading  The order of execution 2.
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
1/32 This Lecture Substitution model An example using the substitution model Designing recursive procedures Designing iterative procedures Proving that.
Concepts of Algorithms CSC-244 Unit 5 and 6 Recursion Shahid Iqbal Lone Computer College Qassim University K.S.A.
CSE 143 Lecture 9 Recursion slides created by Alyssa Harding
CMPT 120 Topic: Searching – Part 2 and Intro to Time Complexity (Algorithm Analysis)
Lecture 11 Recursion. A recursive function is a function that calls itself either directly, or indirectly through another function; it is an alternative.
CS314 – Section 5 Recitation 9
Sections 4.1 & 4.2 Recursive Definitions,
CMSC201 Computer Science I for Majors Lecture 19 – Recursion
Recursion.
Recursion Topic 5.
CMSC201 Computer Science I for Majors Lecture 20 – Recursion (Continued) Prof. Katherine Gibson Based on slides from UPenn’s CIS 110, and from previous.
Topic: Recursion – Part 2
Python: Control Structures
CMSC201 Computer Science I for Majors Lecture 18 – Recursion
Java 4/4/2017 Recursion.
CS1371 Introduction to Computing for Engineers
Recursion
Algorithm Analysis CSE 2011 Winter September 2018.
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Recursion Great fleas have little fleas upon their backs to bite 'em, And little fleas have lesser fleas, and so ad infinitum. And the great fleas themselves,
Testing UW CSE 160 Spring 2018.
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Ruth Anderson UW CSE 160 Winter 2017
Recursion 12-Nov-18.
Recursion "To understand recursion, one must first understand recursion." -Stephen Hawking.
Recursion Output Input
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Applied Algorithms (Lecture 17) Recursion Fall-23
Recursion UW CSE 160 Winter 2017
Recursion Spring 2015 UW CSE 160
Fundamentals of Programming
Recursion 2-Dec-18.
Recursion 2-Dec-18.
CMSC201 Computer Science I for Majors Lecture 19 – Recursion
This Lecture Substitution model
Algorithm Discovery and Design
Ruth Anderson UW CSE 140 Winter 2014
Recursion 29-Dec-18.
Algorithm Discovery and Design
Recursion based on slides by Alyssa Harding
CS302 - Data Structures using C++
Recursion Great fleas have little fleas upon their backs to bite 'em, And little fleas have lesser fleas, and so ad infinitum. And the great fleas themselves,
Recursion Taken from notes by Dr. Neil Moore
Flowcharts and Pseudo Code
This Lecture Substitution model
Recursion 23-Apr-19.
Intro to Computer Science CS1510 Dr. Sarah Diesburg
This Lecture Substitution model
Self-Referencing Functions
Recursion.
Recursion Review Spring 2019 CS 1110
CMPT 120 Lecture 18 – Unit 3 – Graphics and Animation
Lecture 20 – Practice Exercises 4
Lecture 20 – Practice Exercises 4
Lecture 2 - Names & Functions
Recursion Examples.
Presentation transcript:

Lecture 6 - Recursion

Review: Abstraction

def square(x): """Return X * X""" x is a number square returns a non-negative real number square returns the square of x Describing Functions A function's domain is the set of all inputs it might possibly take as arguments. A function's range is the set of output values it might possibly return. A pure function's behavior is the relationship it creates between input and output.

Functional Abstraction Demo Use (functional abstraction) square(2) always returns 4 square(3) always returns 9 ... Without worrying about how Python evaluates the function Mechanics How does Python execute this program line-by-line (e.g. Python Tutor) What happens when you evaluate a call expression, what goes on its body, etc.

Recursion

Suppose you're waiting in line for a concert. You can't see the front of the line, but you want to know what your place in line is. Only the first 100 people get free t- shirts! You can't step out of line because you'd lose your spot. What should you do?

An iterative algorithm might say: Ask my friend to go to the front of the line. Count each person in line one-by-one. Then, tell me the answer.

A recursive algorithm might say: If you're at the front, you know you're first. Otherwise, ask the person in front of you, "What number in line are you?" The person in front of you figures it out by asking the person in front of them who asks the person in front of them etc… Once they get an answer, they tell you and you add one to that answer.

Recursion Recursion is useful for solving problems with a naturally repeating structure - they are defined in terms of themselves It requires you to find patterns of smaller problems, and to define the smallest problem possible

Recursion in Evaluation f(g(h(2), True), h(x)) g(h(2), True) h(x) A call expression is composed of smaller (call) expressions! Stop once you reach a number, boolean, name, etc. h(2)

Recursive Functions

Recursive Functions A function is called recursive if the body of that function calls itself, either directly or indirectly This implies that executing the body of a recursive function may require applying that function multiple times Recursion is inherently tied to functional abstraction

Structure of a Recursive Function One or more base cases, usually the smallest input. "If you're at the front, you know you're first." One or more ways of reducing the problem, and then solving the smaller problem using recursion. "Ask the person in front, 'What number in line are you?'" One or more ways of using the solution to each smaller problem to solve our larger problem. "When the person in front of you figures it out and tells you, add one to that answer." Demo

Functional Abstraction & Recursion Expression fact(1) fact(3) fact(4) fact(n - 1) fact(n) Value 1 6 (3 * 2 * 1) 24 (4 * 3 * 2 * 1) n-1 * n-2 * ... * 1 n * n-1 * n-2 * .. * 1 n * fact(n - 1)

Verifying factorial Is factorial correct? Verify the base cases. Are they correct? Are they exhaustive? Now, harness the power of functional abstraction! Assume that factorial(n-1) is correct. Verify that factorial(n) is correct. def fact(n): if n == 0: return 1 else: return n * fact(n-1) Functional abstraction: don't worry that fact is recursive and just assume that factorial gets the right answer!

Break

Visualizing Recursion Demo

Recursion in Environment Diagrams What is fact(3)? What is fact(2)? The same function fact is called multiple times, each time solving a simpler problem All the frames share the same parent - only difference is the argument What n evaluates to depends upon the current environment What is fact(1)? What is fact(0)? fact(0) is 1

Recursive tree - another way to visualize recursion 6 fact(3) 1 def fact(n): 2 """Calculates n!""" 3 if n == 0: 4 return 1 5 else: 6 return n * fact(n-1) 2 3 * fact(2) 1 2 * fact(1) 1 1 * fact(0) 1

How to Trust Functional Abstraction Assume this all works! Look at how we computed fact(3) Which required computing fact(2) Which required computing fact(1) Which required computing fact(0) Which we know is 1, thanks to the base case! Verifying the correctness of recursive functions Verify that the base cases work as expected For each larger case, verify that it works by assuming the smaller recursive calls are correct

Identifying Patterns Is factorial correct? List out all the cases. def fact(n): if n == 0 or n == 1: return 1 elif n == 2: return 2 * 1 elif n == 3: return 3 * 2 * 1 elif n == 4: return 4 * 3 * 2 * 1 elif n == 5: return 5 * 4 * 3 * 2 * 1 elif n == 6: return 6 * fact(5) else: return n * fact(n-1) Is factorial correct? List out all the cases. Identify patterns between each case. Simplify repeated code with recursive calls.

Examples

Demo Count Up Let’s implement a recursive function to print the numbers from 1 to `n`. Assume `n` is positive. def count_up(n): """Prints the numbers from 1 to n. >>> count_up(1) 1 >>> count_up(2) 2 >>> count_up(4) 3 4 """ "*** YOUR CODE HERE ***" One or more base cases One or more recursive calls with simpler arguments. Using the recursive call to solve our larger problem.

Count Up - Summary Base case What is the smallest number where we don’t have to do any work? We know `n` is positive so the the smallest positive integer is 1 and if n = 1, print it out and do nothing else. Recursive call with smaller arguments Have access to the largest number, so try printing smaller numbers Use recursive call to solve the problem Once we’ve printed up to n - 1, what value is left?

Demo Sum Digits Let’s implement a recursive function to sum all the digits of `n`. Assume `n` is positive. def sum_digits(n): """Calculates the sum of the digits `n`. >>> sum_digits(9) 9 >>> sum_digits(19) 10 >>> sum_digits(2019) 12 """ "*** YOUR CODE HERE ***" One or more base cases One or more recursive calls with simpler arguments. Using the recursive call to solve our larger problem.

Sum Digits Discussion What’s our: Input? Number Smaller problem? Output? Sum of all the digits Base case? A single digit Smaller problem? Sum of all digits but one Larger problem? Sum of all digits but one plus the digit that was left out

Iteration vs. Recursion Iteration and recursion are somewhat related Converting iteration to recursion is formulaic, but converting recursion to iteration can be more tricky Iterative Recursive def fact_iter(n): total, k = 1, 1 while k <= n: total, k = total*k, k+1 return total def fact(n): if n == 0: return 1 else: return n * fact(n-1) Names: n, total, k, fact_iter Names: n, fact

Summary Recursive functions are functions that call themselves in their body one or more times This allows us to break the problem down into smaller pieces Using functional abstraction, we do not have to worry about how those smaller problems are solved A recursive function has a base case to define its smallest problem, and one or more recursive calls If we know the base case is correct, and that we get the correct solution assuming the recursive calls work, then we know the function is correct Evaluating recursive calls follow the same rules we’ve talked about so far