A Function that Calls Itself. It Doesn t Do Anything! Defining a Recursive Function. 2) Base Case. 1) Divide and Conquer 11/22/2010

Similar documents
a function that calls itself It doesn t do anything! Defining a recursive function 1) divide and conquer 2) base case 6/21/2018 chapter 15

CS150 - Sample Final

CS150 Sample Final. Name: Section: A / B

The Practice of Computing Using PYTHON. Chapter 4. Working with Strings. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

CMSC 132: Object-Oriented Programming II. Recursive Algorithms. Department of Computer Science University of Maryland, College Park

CS150 Sample Final Solution

UNIT 5A Recursion: Basics. Recursion

Recursion. Comp Sci 1575 Data Structures. Introduction. Simple examples. The call stack. Types of recursion. Recursive programming

The Practice of Computing Using PYTHON

A library of recursive functions

Programming Training kiddo. Main Points: - Python Statements - Problems with selections.

Module 05: Types of recursion

12. Recursion. n (n 1)!, otherwise. Educational Objectives. Mathematical Recursion. Recursion in Java: 1, if n 1. n! =

Last week. Another example. More recursive examples. How about these functions? Recursive programs. CSC148 Intro. to Computer Science

DM536 Introduction to Programming. Peter Schneider-Kamp.

recursive algorithms 1

What is a Class? Short Answer. Responding to Messages. Everything in Python is an Object 11/8/2010

RECURSION, RECURSION, (TREE) RECURSION! 2

Test Bank Ver. 5.0: Data Abstraction and Problem Solving with C++: Walls and Mirrors, 5 th edition, Frank M. Carrano

The Practice of Computing Using PYTHON. Chapter 2. Control. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Comp 249 Programming Methodology Chapter 11 Recursion

Recursion. Genome 559: Introduction to Statistical and Computational Genomics Elhanan Borenstein

11. Recursion. n (n 1)!, otherwise. Mathematical Recursion. Recursion in Java: Infinite Recursion. 1, if n 1. n! =

Functions and Recursion

Week - 03 Lecture - 18 Recursion. For the last lecture of this week, we will look at recursive functions. (Refer Slide Time: 00:05)

The Art of Recursion: Problem Set 10

Solving problems by recursion

n! = 1 * 2 * 3 * 4 * * (n-1) * n

RECURSION 3. 1 Recursion COMPUTER SCIENCE 61A. June 30, 2016

Two Approaches to Algorithms An Example (1) Iteration (2) Recursion

: Intro Programming for Scientists and Engineers Assignment 1: Turtle Graphics

RECURSION: n. SEE RECURSION 3

Discussion 2C Notes (Week 5, February 4) TA: Brian Choi Section Webpage:

Recursive Problem Solving

6.001 Notes: Section 4.1

Recursion. What is Recursion? Simple Example. Repeatedly Reduce the Problem Into Smaller Problems to Solve the Big Problem

Fractals and L- Systems

Department of Electrical Engineering and Computer Science MASSACHUSETTS INSTITUTE OF TECHNOLOGY

Discussion 2C Notes (Week 5, February 4) TA: Brian Choi Section Webpage:

def F a c t o r i a l ( n ) : i f n == 1 : return 1 else : return n F a c t o r i a l ( n 1) def main ( ) : print ( F a c t o r i a l ( 4 ) )

Recursion. COMS W1007 Introduction to Computer Science. Christopher Conway 26 June 2003

CS 2316 Exam 1 Spring 2013

Intro. Scheme Basics. scm> 5 5. scm>

CSE 341 Lecture 5. efficiency issues; tail recursion; print Ullman ; 4.1. slides created by Marty Stepp

CISC 3115 TY3. C21a: Recursion. Hui Chen Department of Computer & Information Science CUNY Brooklyn College. 11/6/2018 CUNY Brooklyn College

Q1 Q2 Q3 Q4 Q5 Total 1 * 7 1 * 5 20 * * Final marks Marks First Question

/633 Introduction to Algorithms Lecturer: Michael Dinitz Topic: Priority Queues / Heaps Date: 9/27/17

RECURSION (CONTINUED)

34. Recursion. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

RECURSION. Many Slides from Ken Birman, Cornell University

Teaching guide: Subroutines

6/4/12. Recursive void Methods. Chapter 11. Vertical Numbers. Vertical Numbers. Vertical Numbers. Algorithm for Vertical Numbers

RECURSION, RECURSION, (TREE) RECURSION! 3

VTU NOTES QUESTION PAPERS NEWS RESULTS FORUMS

Recursion Introduction OBJECTIVES

COMP-202 Unit 8: Recursion. CONTENTS: Recursion in Java More complex examples

COMP 250 Fall Recursive algorithms 1 Oct. 2, 2017

UNIT 5A Recursion: Basics. Recursion

Working with Strings. Husni. "The Practice of Computing Using Python", Punch & Enbody, Copyright 2013 Pearson Education, Inc.

Chapter 13. Recursion. Copyright 2016 Pearson, Inc. All rights reserved.

ECE 2400 Computer Systems Programming Fall 2018 Topic 2: C Recursion

TAIL CALLS, ITERATORS, AND GENERATORS 11

6.00 Notes On Big-O Notation

Reduction & Recursion Overview

NCS 301 DATA STRUCTURE USING C

Algorithms and Programming

PROFESSOR: Last time, we took a look at an explicit control evaluator for Lisp, and that bridged the gap between

Week - 04 Lecture - 01 Merge Sort. (Refer Slide Time: 00:02)

Design and Analysis of Algorithms Prof. Madhavan Mukund Chennai Mathematical Institute. Module 02 Lecture - 45 Memoization

Chapter 10: Recursive Problem Solving

<The von Koch Snowflake Investigation> properties of fractals is self-similarity. It means that we can magnify them many times and after every

CSC 470 Computer Graphics. Fractals

Chapter 3: Modules. Starting Out with Programming Logic & Design. Second Edition. by Tony Gaddis


Algorithm. An algorithm is a computational process for solving a problem. computational: a computer must be able to perform the steps of the process

Emil Sekerinski, McMaster University, Winter Term 16/17 COMP SCI 1MD3 Introduction to Programming

CSE 214 Computer Science II Recursion

INTRODUCTION TO HASKELL

Turn in a printout of your code exercises stapled to your answers to the written exercises at 2:10 PM on Thursday, January 13th.

RECURSION 7. 1 Recursion COMPUTER SCIENCE 61A. October 15, 2012

Lecture 6 CS2110 Spring 2013 RECURSION

Spring Semester 13, Dr. Punch. Exam #1 (2/14), form 1 A

DR. A.P.J. ABDUL KALAM TECHNICAL UNIVERSITY LUCKNOW. Evaluation Scheme & Syllabus. For. B.Tech. First Year (Programming for Problem Solving)

Loops / Repetition Statements

CSE 230 Intermediate Programming in C and C++ Recursion

Data structure and algorithm in Python

SCHEME 10 COMPUTER SCIENCE 61A. July 26, Warm Up: Conditional Expressions. 1. What does Scheme print? scm> (if (or #t (/ 1 0)) 1 (/ 1 0))

ENVIRONMENT DIAGRAMS AND RECURSION 2

Python. Tutorial Lecture for EE562 Artificial Intelligence for Engineers

Recursion. Chapter 5

Functions. CS10001: Programming & Data Structures. Sudeshna Sarkar Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

The Beauty and Joy of Computing 1 Lab Exercise 9: Problem self-similarity and recursion - Python version

Honors Computer Science Python Mr. Clausen Program 7A, 7B

Recursion vs Induction

Lecture P6: Recursion

Recursion. Chapter 7. Copyright 2012 by Pearson Education, Inc. All rights reserved

CS116 - Module 5 - Accumulative Recursion

Computer and Programming: Lab 1

ENGG1811 Computing for Engineers Week 10 Recursion, External Application Interfacing

Chapter 12. UML and Patterns. Copyright 2008 Pearson Addison-Wesley. All rights reserved

Transcription:

The Practice of Computing Using PYTHON William Punch Richard Enbody Chapter 16 Recursion: Another Control Mechanism A Function that Calls Itself The very basic meaning of a recursive function is a function that calls itself. Leads to some funny definitions: Def: recursion. see recursion However, when you first see it, it looks odd. Look at the recursive function that calculates factorial (code listing 16-2). Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1 2 It Doesn t Do Anything! This is a common complaint when one first sees a recursive function: What exactly is it doing? It doesn t seem to do anything! Our goal is to understand what it means to write a recursive function from a programmer s and computer s point of view. Defining a Recursive Function 3 4 1) Divide and Conquer 2) Base Case Recursion is a natural outcome of a divide and conquer approach to problem solving. A recursive function defines how to break a problem down (divide) and how to reassemble (conquer) the sub-solutions into an overall solution. Recursion is a process not unlike loop iteration. You must define how long (how many iterations) recursion will proceed until it stops. The base case defines this limit. Without the base case, recursion will continue infinitely (just like an infinite loop). 5 6 1

Simple Example Lao-Tzu: A journey of 1000 miles begins with a single step. Code Listing 16-1 def journey (steps): the first step is easy (base case) the n th step is easy having completed the previous n-1 steps (divide and conquer) 7 8 def takestep(n): if n == 1: # base case return "Easy" thisstep = "step(" + str(n) + ") # divide step, recurse previoussteps = takestep(n-1) # conquer step return thisstep + " + " + previoussteps Factorial You remember factorial? Factorial(4) = 4! = 4 * 3 * 2 * 1 The result of the last step, multiply by 1, is defined based on all the previous results that have been calculated. 9 10 Code Listing 16-2 def factorial(n): """Recursive factorial.""" if n == 1: return 1 return n * factorial(n-1) 11 12 2

Trace the Calls 4! = 4 * 3! start first function invocation 3! = 3! * 2 start second function invocation 2! = 2 * 1! start third function invocation 1! = 1 fourth invocation, base case 2! = 2 * 1 = 2 third invocation finishes 3! = 3 * 2 = 6 second invocation finishes 4! = 4 * 6 = 24 first invocation finishes Another: Fibonacci Depends on the Fibo results for the two previous values in the sequence. The base values are Fibo(0) == 1 and Fibo(1) == 1. Fibo (x) = fibo(x-1) + fibo(x-2) 13 14 Code Listing 16-3 def fibo(n): """Recursive Fibonacci sequence.""" if n == 0 or n == 1: # base case return 1 # divide and conquer return fibonacci(n-1) + fibonacci(n-2) 15 16 Trace Reverse String fibo(4) = fibo(3) + fibo(2) fibo(3) = fibo(2) + fibo(1) fibo(2) = fibo(1) + fibo(0) = 2 # base case fibo(3) = 2 + fibo(1) = 3 # base case fibo(4) = 3 + 2 = 5 We know Python has a very simple way to reverse a string, but let s see if we can write a recursive function that reverses a string without using slicing. 17 18 3

Code Listing 16-4 Template for Reversal def reverser (astr): # base case # recursive step # divide into parts # conquer/reassemble thestr = raw_input("reverse what string:") result = reverser(thestr) 19 20 Base Case What string do we know how to trivially reverse? Yes, a string with one character, when reversed, gives back exactly the same string. We use this as our base case. Code Listing 16-5 21 22 def reverser (astr): if len(astr) == 1: # base case return astr # recursive step # divide into parts # conquer/reassemble thestr = raw_input("reverse what string: ") result = reverser(thestr) print Reverse of %s is %s\n" % (thestr,result) Recursive Step We must base the recursive step on what came before, plus the extra step we are presently in. Thus the reverse of a string is the reverse of all but the first character of the string, which is placed at the end. We assume the rev function will reverse the rest: rev(s) = rev(s[1:]) + s[0] 23 24 4

Code Listing 16-6 def reverse (astr): """Recursive reverse a string.""" print "Got as an argument:",astr if len(astr) == 1: print "Base Case!" return astr newstr =reverse(astr[1:]) + astr[0] print "Reassemble%s and %s into %s %\ (astr[1:],astr[0],newstr) return newstr 25 26 Got as an argument: abcde Got as an argument: bcde Got as an argument: cde Got as an argument: de Got as an argument: e Base Case! Reassembling e and d into ed Reassembling de and c into edc Reassembling cde and b into edcb Reassembling bcde and a into edcba How Does Python Keep Track? 27 28 The Stack A Stack is a data structure, like a List or a Dictionary, but with a few different characteristics. A Stack is a sequence. A Stack only allows access to one end of its data, the top of the stack. 29 30 5

Operations pop: remove top of stack. Stack is one element smaller. push (val): add val to the stack. Val is now the top. Stack is one element larger. top: Reveals the top of the stack. No modification to stack. 31 32 Stack of Function Calls Python maintains a stack of function calls. If a function calls another function recursively, the new function is pushed onto the calling stack and the previous function waits. The top is always the active function. When a pop occurs, the function below becomes active. Code Listing 16-7 33 34 def factorial(n): """Recursive Factorial with print """ indent = 4*(6-n)*" " #indent based on fun. depth print indent + "Enter factorial n = ", n if n == 1: # base case print indent + "Base case." return 1 # recursive case print indent + "Before call f(" + str(n-1) + ")" rest = factorial(n-1) # separate recursive call print indent + "After call f(" + str(n-1) + ") \ = ", rest return n * rest >>> factorial(4) Enter factorial n = 4 Before recursive call f(3) Enter factorial n = 3 Before recursive call f(2) Enter factorial n = 2 Before recursive call f(1) Enter factorial n = 1 Base case. After recursive call f(1) = 1 After recursive call f(2) = 2 After recursive call f(3) = 6 24 35 36 6

Recursive Figures 37 38 Fractal Objects You can use recursion to draw many realworld figures. Fractals are a class of drawing that have a couple of interesting properties: upon magnification, the shape of the figure remains the same the resulting figure has a floating point dimensionality value (2.35 D for example) 1. Draw an edge 2. turn left Draw a tree 3. draw edge and left branch # recurse 4. turn right 5. draw edge and right branch #recurse 6. turn left 7. backup 39 40 Code Listing 16-8 41 from turtle import * def branch(length, level): if level <= 0: # base case return forward(length) left(45) branch(0.6*length, level-1) # recurse right(90) branch(0.6*length, level-1) # recurse left(45) backward(length) return left(90) branch(100,5) 42 7

Couple of Things Note that length is reduced as we recurse down (making for shorter branches). The numbers on the right of the following picture show the order in which the branches are drawn. 43 44 Sierpinski Triangles A little simpler than the tree: 1.draw edge 2.recurse 3.backward 4.turn 120 degrees Code Listing 16-9 45 46 from turtle import * def sierpinski(length, depth): if depth > 1: dot() # mark position to trace if depth == 0: # base case stamp() # stamp triangular shape forward(length) sierpinski(length/2, depth-1)# recursive call backward(length) left(120) forward(length) sierpinski(length/2, depth-1)# recursive call backward(length) left(120) forward(length) sierpinski(length/2, depth-1)# recursive call backward(length) left(120) sierpinski(200,6) 47 48 8

Some Recursive Details Recursive functions are easy to write, and they lend themselves to divide and conquer. They can be slow (all the pushing and popping on the stack). Can be converted from recursive to iterative, but that can be hard depending on the problem. 49 9