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.

Slides:



Advertisements
Similar presentations
Genome 559: Introduction to Statistical and Computational Genomics
Advertisements

C++ Programming:. Program Design Including
Lilian Blot Recursion Autumn 2012 TPOP 1. Lilian Blot Recursion Autumn 2012 TPOP 2.
MATH 224 – Discrete Mathematics
Recursion Genome 559: Introduction to Statistical and Computational Genomics Elhanan Borenstein.
Factorial Recursion stack Binary Search Towers of Hanoi
COMPSCI 105 S Principles of Computer Science Recursion 1.
Recursion. Binary search example postponed to end of lecture.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 16: Recursion.
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
Recursion.
Chapter 11 Recursion Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Data Structures Using C++ 2E Chapter 6 Recursion.
Data Structures Using C++ 2E Chapter 6 Recursion.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12: Recursion Problem Solving, Abstraction, and Design using C++
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 17: Recursion.
A Computer Science Tapestry 1 Recursion (Tapestry 10.1, 10.3) l Recursion is an indispensable technique in a programming language ä Allows many complex.
Chapter 13 Recursion. Topics Simple Recursion Recursion with a Return Value Recursion with Two Base Cases Binary Search Revisited Animation Using Recursion.
1 Decrease-and-Conquer Approach Lecture 06 ITS033 – Programming & Algorithms Asst. Prof. Dr. Bunyarit Uyyanonvara IT Program, Image and Vision Computing.
Comp 249 Programming Methodology Chapter 10 – Recursion Prof. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,
Recursion.
Recursion. Review  Recursive solutions, by definition, are built off solutions to sub-problems.  Many times, this will mean simply to compute f(n) by.
Lecturer: Dr. AJ Bieszczad Chapter 11 COMP 150: Introduction to Object-Oriented Programming 11-1 l Basics of Recursion l Programming with Recursion Recursion.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 19 : Recursion King Fahd University of Petroleum & Minerals College of Computer.
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 Department Data Structure & Algorithms Lecture 8 Recursion.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 17: Recursion.
Reading – Chapter 10. Recursion The process of solving a problem by reducing it to smaller versions of itself Example: Sierpinski’s TriangleSierpinski’s.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
Chapter 13 Recursion. Learning Objectives Recursive void Functions – Tracing recursive calls – Infinite recursion, overflows Recursive Functions that.
Fall Week 4 CSCI-141 Scott C. Johnson.  Computers can process text as well as numbers ◦ Example: a news agency might want to find all the articles.
CSIS 123A Lecture 9 Recursion Glenn Stevenson CSIS 113A MSJC.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Recursive Solutions Recursion is an extremely powerful problem-solving.
Data Structures R e c u r s i o n. Recursive Thinking Recursion is a problem-solving approach that can be used to generate simple solutions to certain.
Java Programming: Guided Learning with Early Objects Chapter 11 Recursion.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
CHP-3 STACKS.
Chapter 15: Recursion. Objectives In this chapter, you will: – Learn about recursive definitions – Explore the base case and the general case of a recursive.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 16: Recursion.
Chapter 15: Recursion. Recursive Definitions Recursion: solving a problem by reducing it to smaller versions of itself – Provides a powerful way to solve.
Chapter 15: Recursion. Objectives In this chapter, you will: – Learn about recursive definitions – Explore the base case and the general case of a recursive.
1 Recursion Recursive function: a function that calls itself (directly or indirectly). Recursion is often a good alternative to iteration (loops). Its.
CS 116 Object Oriented Programming II Lecture 13 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
CSC 143 P 1 CSC 143 Recursion [Chapter 5]. CSC 143 P 2 Recursion  A recursive definition is one which is defined in terms of itself  Example:  Compound.
Python Programming, 3/e1 Python Programming: An Introduction to Computer Science Chapter 13 Algorithm Design and Recursion.
CMSC201 Computer Science I for Majors Lecture 19 – Recursion
Chapter 13 Recursion Copyright © 2016 Pearson, Inc. All rights reserved.
Chapter 13 Algorithm Design and Recursion
Recursion CENG 707.
Chapter 15 Recursion.
Recursion DRILL: Please take out your notes on Recursion
Chapter 15 Recursion.
CMSC201 Computer Science I for Majors Lecture 18 – Recursion
Recursion "To understand recursion, one must first understand recursion." -Stephen Hawking.
Algorithm Design and Recursion
Python Programming: An Introduction to Computer Science
賦得古原草送別 ~白居易 離離原上草,一歲一枯榮。 野火燒不盡,春風吹又生。 遠芳侵古道,晴翠接荒城。 又送王孫去,萋萋滿別情。
CS201: Data Structures and Discrete Mathematics I
CMSC201 Computer Science I for Majors Lecture 19 – Recursion
Data Structures Review Session
Programming Thinking and Method (6-7)
Basics of Recursion Programming with Recursion
Recursion Taken from notes by Dr. Neil Moore
Lecture 11 Algorithm Design
And now for something completely different . . .
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Programming with Recursion
Last Class We Covered Recursion Stacks Parts of a recursive function:
Chapter 3 :Recursion © 2011 Pearson Addison-Wesley. All rights reserved.
Presentation transcript:

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 the solution of those sub problems back to get the solution of the original problem.

Python Programming, 2/e 3 Binary Search The basic idea between the binary search algorithm that you have studied earlier was to iteratively divide the problem in half. This technique is known as a divide and conquer approach. Divide and conquer divides the original problem into sub- problems that are smaller versions of the original problem.

Python Programming, 2/e 4 Recursive Problem-Solving In the binary search, the initial range is the entire list. We look at the middle element… if it is the target, we’re done. Otherwise, we continue by performing a binary search on either the top half or bottom half of the list. In the iterative version of Binary Search, you split the list into half after each iteration. If the element is less than the middle, then you search for the lower half of the list in the next iteration, otherwise you search for the higher half of the list. There is another way to similarly solve Binary Search.

Python Programming, 2/e 5 Recursive Algorithm for Binary Search binarySearch(x, low, high, numlist): mid = (low + high)//2 if low > high: return -1 elsif x < nums[mid]: binarySearch(x, low, mid-1, numlist) else: binarySearch(x, mid+1, high, numlist) This version has no loop, and seems to refer to itself! What’s going on??

Python Programming, 2/e 6 Recursive Definitions A description of something that refers to itself is called a recursive definition. In the last example, the binary search algorithm uses its own description – a “call” to binary search “recurs” inside of the definition – hence the label “recursive definition.” The function is calling itself with new parameters. If you notice, the parameters low and high change in every recursive call.

Python Programming, 2/e 7 Recursive Definitions Rules All good recursive definitions have these two key characteristics:  There are one or more base cases for which no recursion is applied.  All chains of recursion eventually end up at one of the base cases. The simplest way for these two conditions to occur is for each recursion to act on a smaller version of the original problem. A very small version of the original problem that can be solved without recursion becomes the base case.

Python Programming, 2/e 8 Recursive Definitions: Math Example In mathematics, recursion is frequently used. The most common example is the factorial: For example, 5! = 5(4)(3)(2)(1), or 5! = 5(4!)

Python Programming, 2/e 9 Factorial Recursive Definition In other words, Or This definition says that 0! is 1, while the factorial of any other number is that number times the factorial of one less than that number.

Python Programming, 2/e 10 Factorial Recursive Definition Our definition is recursive, but definitely not circular. Circular definition will keep on going indefinitely. Recursive definitions on the other hand stops at one point of its execution Consider 4!  4! = 4(4-1)! = 4(3!)  What is 3!? We apply the definition again 4! = 4(3!) = 4[3(3-1)!] = 4(3)(2!)  And so on… 4! = 4(3!) = 4(3)(2!) = 4(3)(2)(1!) = 4(3)(2)(1)(0!) = 4(3)(2)(1)(1) = 24

Python Programming, 2/e 11 Factorial Recursive Definition Factorial is not circular because we eventually get to 0!, whose definition does not rely on the definition of factorial and is just 1. This is called a base case for the recursion. When the base case is encountered, we get a closed expression that can be directly computed.

Python Programming, 2/e 12 Recursive Algorithm for Factorial We’ve seen previously that factorial can be calculated using a loop accumulator. Factorial can be written recursively as: def fact(n): if n == 0: return 1 else: return n * fact(n-1)

Python Programming, 2/e 13 Factorial: Calling recursive function >>> fact(4) 24 >>> fact(10) Remember that each call to a function starts that function a new, with its own copies of local variables and parameters.

Python Programming, 2/e 14 Diagrammatic Representation

Python Programming, 2/e 15 Example: String Reversal Python lists have a built-in method that can be used to reverse the list. What if you wanted to reverse a string? If you wanted to program this yourself, one way to do it would be to convert the string into a list of characters, reverse the list, and then convert it back into a string.

Python Programming, 2/e 16 Example: String Reversal Using recursion, we can calculate the reverse of a string without the intermediate list step. Think of a string as a recursive object:  Divide it up into a first character and “all the rest”  Reverse the “rest” and append the first character to the end of it

Python Programming, 2/e 17 Example: String Reversal def reverse(s): return reverse(s[1:]) + s[0] The slice s[1:] returns all but the first character of the string. We reverse this slice and then concatenate the first character ( s[0] ) onto the end.

Python Programming, 2/e 18 Example: String Reversal >>> reverse("Hello") Traceback (most recent call last): File " ", line 1, in -toplevel- reverse("Hello") File "C:/Program Files/Python 2.3.3/z.py", line 8, in reverse return reverse(s[1:]) + s[0] File "C:/Program Files/Python 2.3.3/z.py", line 8, in reverse return reverse(s[1:]) + s[0] … File "C:/Program Files/Python 2.3.3/z.py", line 8, in reverse return reverse(s[1:]) + s[0] RuntimeError: maximum recursion depth exceeded What happened? There were 1000 lines of errors!

Python Programming, 2/e 19 Example: String Reversal Remember: To build a correct recursive function, we need a base case that doesn’t use recursion. We forgot to include a base case, so our program is an infinite recursion. Each call to reverse contains another call to reverse, so none of them return.

Python Programming, 2/e 20 Example: String Reversal Each time a function is called it takes some memory. Python stops it at 1000 calls, the default “maximum recursion depth.” What should we use for our base case? Following our algorithm, we know we will eventually try to reverse the empty string. Since the empty string is its own reverse, we can use it as the base case.

Python Programming, 2/e 21 Example: String Reversal def reverse(s): if s == "": return s else: return reverse(s[1:]) + s[0] >>> reverse("Hello") 'olleH'

Python Programming, 2/e 22 Example: Anagrams An anagram is formed by rearranging the letters of a word. Anagram formation is a special case of generating all permutations (rearrangements) of a sequence, a problem that is seen frequently in mathematics and computer science.

Python Programming, 2/e 23 Example: Anagrams Let’s apply the same approach from the previous example.  Slice the first character off the string.  Place the first character in all possible locations within the anagrams formed from the “rest” of the original string.

Python Programming, 2/e 24 Example: Anagrams Suppose the original string is “abc”. Stripping off the “a” leaves us with “bc”. Generating all anagrams of “bc” gives us “bc” and “cb”. To form the anagram of the original string, we place “a” in all possible locations within these two smaller anagrams: [“abc”, “bac”, “bca”, “acb”, “cab”, “cba”]

Python Programming, 2/e 25 Example: Anagrams As in the previous example, we can use the empty string as our base case. def anagrams(s): if s == "": return [s] else: ans = [] for w in anagrams(s[1:]): for pos in range(len(w)+1): ans.append(w[:pos]+s[0]+w[pos:]) return ans

Python Programming, 2/e 26 Example: Anagrams A list is used to accumulate results. The outer for loop iterates through each anagram of the tail of s. The inner loop goes through each position in the anagram and creates a new string with the original first character inserted into that position. The inner loop goes up to len(w)+1 so the new character can be added at the end of the anagram.

Python Programming, 2/e 27 Example: Anagrams w[:pos]+s[0]+w[pos:]  w[:pos] gives the part of w up to, but not including, pos.  w[pos:] gives everything from pos to the end.  Inserting s[0] between them effectively inserts it into w at pos.

Python Programming, 2/e 28 Example: Anagrams The number of anagrams of a word is the factorial of the length of the word. >>> anagrams("abc") ['abc', 'bac', 'bca', 'acb', 'cab', 'cba']

QUESTIONS? 29