CMSC201 Computer Science I for Majors Lecture 16 – Recursion

Slides:



Advertisements
Similar presentations
LEVEL II, TERM II CSE – 243 MD. MONJUR-UL-HASAN LECTURER DEPT OF CSE, CUET Recursive & Dynamic Programming.
Advertisements

Recursion Genome 559: Introduction to Statistical and Computational Genomics Elhanan Borenstein.
Recursion vs. Iteration The original Lisp language was truly a functional language: –Everything was expressed as functions –No local variables –No iteration.
8 Algorithms Foundations of Computer Science ã Cengage Learning.
Chapter 16 Recursion: Another Control Mechanism. "The Practice of Computing Using Python", Punch & Enbody, Copyright © 2013 Pearson Education, Inc. a.
© 2004 Goodrich, Tamassia Using Recursion1 Programming with Recursion.
Fundamentals of Computer Science Lecture 14: Recursion Instructor: Evan Korth New York University.
Computer Science II Recursion Professor: Evan Korth New York University.
Recursion Introduction to Computing Science and Programming I.
Fundamentals of Computer Science Lecture 14: Recursion Instructor: Evan Korth New York University.
Recursion. 2 CMPS 12B, UC Santa Cruz Solving problems by recursion How can you solve a complex problem? Devise a complex solution Break the complex problem.
CS 206 Introduction to Computer Science II 10 / 14 / 2009 Instructor: Michael Eckmann.
Recursion Road Map Introduction to Recursion Recursion Example #1: World’s Simplest Recursion Program Visualizing Recursion –Using Stacks Recursion Example.
1 Chapter 18 Recursion Dale/Weems/Headington. 2 Chapter 18 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions.
CS 206 Introduction to Computer Science II 10 / 15 / 2008 Instructor: Michael Eckmann.
Recursion.
Recursion. What is recursion? Solving a problem in terms of itself or repeating objects in a “self-similar” way A recursive function is a function that.
1 CS 177 Week 16 Recitation Recursion. 2 Objective To understand and be able to program recursively by breaking down a problem into sub problems and joining.
1 Lecture 14 Chapter 18 - Recursion. 2 Chapter 18 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions l Writing.
1 Chapter 13 Recursion. 2 Chapter 13 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions l Writing Recursive.
Recursion Textbook chapter Recursive Function Call a recursive call is a function call in which the called function is the same as the one making.
Computer Science and Software Engineering University of Wisconsin - Platteville 9. Recursion Yan Shi CS/SE 2630 Lecture Notes Partially adopted from C++
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
IB Computer Science Unit 5 – Advanced Topics Recursion.
Recursion Unit 15. Recursion: Recursion is defined as the process of a subprogram calling itself as part of the solution to a problem. It is a problem.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
1 Recursion. 2 Chapter 15 Topics  Meaning of Recursion  Base Case and General Case in Recursive Function Definitions  Writing Recursive Functions with.
© Janice Regan, CMPT 128, February CMPT 128: Introduction to Computing Science for Engineering Students Recursion.
8.1 8 Algorithms Foundations of Computer Science  Cengage Learning.
General Computer Science for Engineers CISC 106 Lecture 06 James Atlas Computer and Information Sciences 06/24/2009.
Recursion1 © 2013 Goodrich, Tamassia, Goldwasser.
CS 116 Object Oriented Programming II Lecture 13 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
CMSC201 Computer Science I for Majors Lecture 19 – Recursion (Continued) Prof. Katherine Gibson Prof. Jeremy Dixon Based on slides from UPenn’s.
Recursion Powerful Tool
Recursion.
CMSC201 Computer Science I for Majors Lecture 19 – Recursion
Recursion.
Chapter 13 Recursion Copyright © 2016 Pearson, Inc. All rights reserved.
CMSC201 Computer Science I for Majors Lecture 20 – Recursion (Continued) Prof. Katherine Gibson Based on slides from UPenn’s CIS 110, and from previous.
Introduction to Recursion
Introduction to Recursion
OBJECT ORIENTED PROGRAMMING II LECTURE 23 GEORGE KOUTSOGIANNAKIS
Revised based on textbook author’s notes.
Introduction to Computing Science and Programming I
CMSC201 Computer Science I for Majors Lecture 18 – Recursion
Topic: Recursion – Part 1
Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg
To understand recursion, you have to understand recursion!
Programming with Recursion
Last Class We Covered Data representation Binary numbers ASCII values
Fundamentals of Programming
Log onto a computer first then ….
CMSC201 Computer Science I for Majors Lecture 19 – Recursion
Last Class We Covered Dictionaries Hashing Dictionaries vs Lists
Coding Concepts (Basics)
CMSC201 Computer Science I for Majors Lecture 17 – Recursion (cont)
Programming with Recursion
Recursion Taken from notes by Dr. Neil Moore
Yan Shi CS/SE 2630 Lecture Notes
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Programming with Recursion
Chapter 18 Recursion.
Last Class We Covered Recursion Stacks Parts of a recursive function:
CMSC201 Computer Science I for Majors Lecture 12 – Program Design
Lecture 20 – Practice Exercises 4
Introduction to Computer Science
Lecture 6 - Recursion.
Presentation transcript:

CMSC201 Computer Science I for Majors Lecture 16 – Recursion

Last Class We Covered What makes “good code” good Readability Adaptability Commenting guidelines Incremental development

Any Questions from Last Time?

Today’s Objectives To introduce recursion To better understand the concept of “stacks” To begin to learn how to “think recursively” To look at examples of recursive code Summation, factorial, etc.

Introduction to Recursion

What is Recursion? In computer science, recursion is a way of thinking about and solving problems It’s actually one of the central ideas of CS In recursion, the solution depends on solutions to smaller instances of the same problem

Recursive Solutions When creating a recursive solution, there are a few things we want to keep in mind: We need to break the problem into smaller pieces of itself We need to define a “base case” to stop at The smaller problems we break down into need to eventually reach the base case

Normal vs Recursive Functions So far, we’ve had functions call other functions For example, main() calls the square() function A recursive function, however, calls itself main() square() countdown()

Why Would We Use Recursion? In computer science, some problems are more easily solved by using recursive methods For example: Traversing through a directory or file system Traversing through a tree of search results Some sorting algorithms recursively sort data For today, we will focus on the basic structure of using recursive methods

Toy Example of Recursion def countdown(intInput): print(intInput) if (intInput > 2): countdown(intInput-1) def main(): countdown(50) main() This is where the recursion occurs. You can see that the countdown() function calls itself. What does this program do? This program prints the numbers from 50 down to 2.

Visualizing Recursion To understand how recursion works, it helps to visualize what’s going on Python uses a stack to keep track of function calls A stack is an important computer science concept To help visualize, we will

Stacks

Stacks A stack is like a bunch of lunch trays in a cafeteria It has only two operations: Push You can push something onto the top of the stack Pop You can pop something off the top of the stack Let’s see an example stack in action

Stack Example In the animation below, we “push 3”, then “push 8”, and then pop twice Time 0 Empty Time 1 Push 3 Time 2 Push 8 Time 3 Pop Time 4 Pop 8 8 3 3 3 3

Stack Details In computer science, a stack is a last in, first out (LIFO) data structure It can store any type of data, but has only two operations: push and pop Push adds to the top of the stack, hiding anything else on the stack Pop removes the top element from the stack

Stack Details The nature of the pop and push operations also means that stack elements have a natural order Elements are removed from the stack in the reverse order to the order of their addition The lower elements are those that have been in the stack the longest

Stack Exercise In your notebooks, trace the following commands, to the stack’s final appearance Push “D” Push “O” Pop Push “G” Push “M” Push “K” Pop Push “T” Push “G” Push “E” Push “F” Pop Push “H” Push “S”

Stacks and Functions When you run your program, the computer creates a stack for you Each time you call a function, the function is pushed onto the top of the stack When the function returns or exits, the function is popped off the stack

Stack Example Run Time 0 Empty Time 1 Time 2 Time 3 Time 4 main() Call main() Time 2 Call square(7) Time 3 square() returns Time 4 main() ends square(7) square(7) main() main() main() main()

Stacks and Recursion If a function calls itself recursively, you push another call to the function onto the stack We now have a simple way to visualize how recursion really works

Toy Example of Recursion def countdown(intInput): print(intInput) if (intInput > 2): countdown(intInput-1) def main(): countdown(50) main() Here’s the code again. Now, that we understand stacks, we can visualize the recursion. We’ll call the function with a value of just 4 for the trace. We’ll also shorten it to cDown().

Stack and Recursion in Action Skipping time step 0, start by pushing main()… Time 1 Time 2 Time 3 Time 4 Time 5 Time 8 cDown(2) cDown(2) cDown(3) cDown(3) cDown(3) cDown(4) cDown(4) cDown(4) cDown(4) main() main() main() main() main() main() Time 6, 7…

Defining Recursion

“Cases” in Recursion A recursive function must have two things: At least one base case When a result is returned (or the function ends) “When to stop” At least one recursive case When the function is called again with new inputs “When to go (again)”

Terminology def fxn(n): if n == 1: return 1 else: return fxn(n - 1) Notice that the recursive call is passing in simpler input, approaching the base case base case recursive case recursive call

Recursion Example What is summ (1) ? What is summ (2) ? def summ(n): if n == 1: return 1 else: return n + summ (n - 1) What is summ (1) ? What is summ (2) ? What is summ (100) ? We at least know that it’s 100 + summ(99)

Recursion Example def summ(n): if n == 1: return 1 else: return n + summ (n - 1) summ(3) 3 + summ(2) 2 + summ(1) 1 3 + 2 + 1 = 6

Factorials 4! = 4 × 3 × 2 × 1 = 24 Does anyone know the value of 9! ? 362,880 Does anyone know the value of 10! ? How did you know?

Factorial 9! = 9×8×7×6×5×4×3×2×1 10! = 10 × 9×8×7×6×5×4×3×2×1 9! = 9×8×7×6×5×4×3×2×1 10! = 10 × 9×8×7×6×5×4×3×2×1 10! = 10 × 9! n! = n × (n - 1)! That's a recursive definition! The answer to a problem can be defined as a smaller piece of the original problem

What happened? What went wrong? Factorial def fact(n): return n * fact(n - 1) fact(3) 3 * fact(2) 2 * fact(1) 1 * fact(0) 0 * fact(-1) ... What happened? What went wrong?

Factorial (Fixed) def fact(n): if n == 0: return 1 else: return n * fact(n - 1) fact(3) 3 * fact(2) 2 * fact(1) 1 * fact(0) 1

Recursion Practice

Thinking Recursively Anything we can do with a while loop can also be accomplished through recursion Let’s get some practice by transforming basic loops into a recursive function To keep in mind: What is the base case? The recursive case? Are we returning values, and if so, how?

Non-Recursive sumList() Sum the contents of a list together def sumList(numList): total = 0 for i in range(len(numList)): total = total + numList[i] return total Transform this into a recursive function

this return is very important Recursive sumList() Recursively sum the contents of a list together def recSumList(currList, index, total): # BASE CASE: reached the end of the list if index == len(currList): return total else: total += currList[index] # RECURSIVE CALL: call with updated index return recSumList(currList, index+1, total) this return is very important

Recursive sumList() Recursively sum the contents of a list together def recSumList(currList, index): # BASE CASE: reached the end of the list if index == len(currList): return 0 else: # RECURSIVE CALL: add this element to rest of list print("Adding", currList[index], "to total") return currList[index] + \ recSumList( currList, index+1 )

Recursive Thinking Sometimes, creating a recursive function requires us to think about the problem differently What kind of base case do we need for summing a list together? How do we know we’re “done”? Instead of approaching the problem as before, you could think of it instead as adding the first element to the sum of the rest of the list

Recursive Summing What is the base case here? myList = [3, 5, 8, 7, 2, 6, 1] 3 + [5, 8, 7, 2, 6, 1] 5 + [8, 7, 2, 6, 1] 8 + [7, 2, 6, 1] etc... What is the base case here? How does the recursive case work?

again, this return is very important Recursive sumList() Recursively sum the contents of a list together def recSumList(currList): # BASE CASE: no elements left (empty list) if len(currList) == 0: return 0 else: # RECURSIVE CALL: add first element to rest of list print("Adding", currList[0], "to", currList[1:] ) return currList[0] + recSumList( currList[1:] ) again, this return is very important

Daily CS History Margaret Hamilton Who is she? Coined the term The original Hamilton Worked for MIT and NASA Coined the term “Software Engineer”

Daily CS History Famous for this picture Standing next to printed out code needed for the navigation system on the Apollo missions She focused on error detection in software

Announcements Project 2 is out on Blackboard now Midterm #2 Design is due by Friday (Nov 2nd) at 8:59:59 PM Project is due by Friday (Nov 9th) at 8:59:59 PM Midterm #2 Cumulative, but weighted towards recent topics November 14th and 15th in class SDS students schedule your exam ASAP

Image Sources Pancake drizzle: Margaret Hamilton http://www.topwithcinnamon.com/2013/01/2-ingredient-healthy-pancakes-gluten-free-dairy-free.html Margaret Hamilton https://en.wikipedia.org/wiki/File:Margaret_Hamilton_in_action.jpg https://upload.wikimedia.org/wikipedia/commons/d/db/Margaret_Hamilton_-_restoration.jpg