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

Similar documents
RECURSION, RECURSION, (TREE) RECURSION! 3

RECURSION, RECURSION, (TREE) RECURSION! 2

RECURSION, RECURSION, (TREE) RECURSION! 3

ENVIRONMENT DIAGRAMS AND RECURSION 2

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

RECURSION: n. SEE RECURSION 3

ITERATION AND RECURSION 3

ENVIRONMENT DIAGRAMS AND RECURSION 2

Environment Diagrams and Recursion Fall 2017 Discussion 2: September 6, 2017 Solutions. 1 More Environment Diagrams

RECURSION AND LINKED LISTS 3

CS 61A Higher Order Functions and Recursion Fall 2018 Discussion 2: June 26, Higher Order Functions. HOFs in Environment Diagrams

CS 61A Higher Order Functions and Recursion Fall 2018 Discussion 2: June 26, 2018 Solutions. 1 Higher Order Functions. HOFs in Environment Diagrams

COMP-202: Foundations of Programming. Lecture 13: Recursion Sandeep Manjanna, Summer 2015

Module 05: Types of recursion

CSCI 121: Recursive Functions & Procedures

TAIL RECURSION, SCOPE, AND PROJECT 4 11

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

Interpreters and Tail Calls Fall 2017 Discussion 8: November 1, 2017 Solutions. 1 Calculator. calc> (+ 2 2) 4

DM502 Programming A. Peter Schneider-Kamp.

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

Admin. How's the project coming? After these slides, read chapter 13 in your book. Quizzes will return

DM550/DM857 Introduction to Programming. Peter Schneider-Kamp

61A LECTURE 6 RECURSION. Steven Tang and Eric Tzeng July 2, 2013

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 ) )

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))

CSI33 Data Structures

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

CS116 - Module 5 - Accumulative Recursion

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

DM536 Introduction to Programming. Peter Schneider-Kamp.

UNIT 5A Recursion: Basics. Recursion

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

RACKET BASICS, ORDER OF EVALUATION, RECURSION 1

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

APCS-AB: Java. Recursion in Java December 12, week14 1

Programming for Engineers in Python

CS1 Lecture 15 Feb. 19, 2018

DM536 / DM550 Part 1 Introduction to Programming. Peter Schneider-Kamp.

Algorithm Design and Recursion. Search and Sort Algorithms

Functions and Recursion

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

SCHEME AND CALCULATOR 5b

INTERPRETERS 8. 1 Calculator COMPUTER SCIENCE 61A. November 3, 2016

CS1 Recitation. Week 2

OVERVIEW. Recursion is an algorithmic technique where a function calls itself directly or indirectly. Why learn recursion?

Recursion CS GMU

Koch snowflake. Fractal Fern

Recursive Definitions

recursive algorithms 1

ORDERS OF GROWTH, DATA ABSTRACTION 4

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

# track total function calls using a global variable global fibcallcounter fibcallcounter +=1

Outline. Simple Recursive Examples Analyzing Recursion Sorting The Tower of Hanoi Divide-and-conquer Approach In-Class Work. 1 Chapter 6: Recursion

Standard Version of Starting Out with C++, 4th Edition. Chapter 19 Recursion. Copyright 2003 Scott/Jones Publishing

SCHEME The Scheme Interpreter. 2 Primitives COMPUTER SCIENCE 61A. October 29th, 2012

UNIT 5A Recursion: Basics. Recursion

Spring 2018 Discussion 7: March 21, Introduction. 2 Primitives

Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives

TAIL CALLS, ITERATORS, AND GENERATORS 11

Wentworth Institute of Technology COMP1050 Computer Science II Spring 2017 Derbinsky. Recursion. Lecture 13. Recursion

Recursion CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2011

INTERPRETERS AND TAIL CALLS 9

Fall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives

DM536 Introduction to Programming. Peter Schneider-Kamp.

Lecture Notes 4 More C++ and recursion CSS 501 Data Structures and Object-Oriented Programming Professor Clark F. Olson

Structure and Interpretation of Computer Programs

Conditionals: Making Choices

Autumn 2012 November 7 th 9 th, 2012 Section Solution

61A LECTURE 22 TAIL CALLS, ITERATORS. Steven Tang and Eric Tzeng July 30, 2013

Midterm Review. CS61A Summer Katya Stukalova Jerome Baek

Measuring Efficiency

15-122: Principles of Imperative Computation, Fall 2015

EXAM PREPARATION SECTION 1

Midterm 1 Review Fall 2017 September 8, Functions. Instructions

CSE 230 Intermediate Programming in C and C++ Recursion

Homework 3: Recursion Due: 11:59 PM, Sep 25, 2018

Module 10: Imperative Programming, Modularization, and The Future

University of Massachusetts Lowell

61A LECTURE 7 DATA ABSTRACTION. Steven Tang and Eric Tzeng July 3, 2013

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

Fruitful Recursion (recursion that returns a value)

CS 61A Interpreters, Tail Calls, Macros, Streams, Iterators. Spring 2019 Guerrilla Section 5: April 20, Interpreters.

STUDENT LESSON A9 Recursion

Recursion. Fundamentals of Computer Science

Reading 8 : Recursion

Recursion. Overview. Mathematical induction. Hello recursion. Recursion. Example applications. Goal: Compute factorial N! = 1 * 2 * 3...

A function that invokes itself is said to

Recursion. So, just as you are allowed to call function B from within function A, you are ALSO allowed to call function A from within function A!

Lecture 10: Recursive Functions. Computer System and programming in C 1

More Complicated Recursion CMPSC 122

Problem Set CVO 103, Spring 2018

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

Homework 7: Subsets Due: 11:59 PM, Oct 23, 2018

CSE200 Lecture 6: RECURSION

CS1 Lecture 15 Feb. 18, 2019

A library of recursive functions

Nonvisual Arrays and Recursion. by Chris Brown under Prof. Susan Rodger Duke University June 2012


Flow Control: Branches and loops

PROBLEM SOLVING 11. July 24, 2012

Transcription:

RECURSION 3 COMPUTER SCIENCE 61A June 30, 2016 A recursive function is a function that calls itself. Here s a recursive function: def factorial(n): if n == 0 or n == 1: return 1 else: return n * factorial(n-1) 1 Recursion Although we haven t finished defining factorial, we are still able to call it since the function body is not evaluated until the function is called. We do have one base case: when n is 0 or 1. Now we can compute factorial(2) in terms of factorial(1), and factorial(3) in terms of factorial(2), and factorial(4) well, you get the idea. There are three common steps in a recursive definition: 1. Figure out your base case: What is the simplest argument we could possibly get? For example, factorial(0) is 1 by definition. 2. Make a recursive call with a simpler argument: Simplify your problem, and assume that a recursive call for this new problem will simply work. This is called the leap of faith. For factorial, we reduce the problem by calling factorial(n-1). 3. Use your recursive call to solve the full problem: Remember that we are assuming the recursive call works. With the result of the recursive call, how can you solve the original problem you were asked? For factorial, we just multiply (n 1)! by n.

DISCUSSION 3: RECURSION Page 2 1.1 Cool recursion questions! 1. Create a recursive countdown function that takes in an integer n and prints out a countdown from n to 1. The function is defined on the next page. First, think about a base case for the countdown function. What is the simplest input the problem could be given? After you ve thought of a base case, think about a recursive call with a smaller argument that approches the base case. What happens if you call countdown(n - 1)? Then, put the base case and the recursive call together, and think about where a print statement would be needed. def countdown(n): >>> countdown(3) 3 2 1 2. Is there an easy way to change countdown to count up instead?

DISCUSSION 3: RECURSION Page 3 2 Iteration vs. Recursion We ve written factorial recursively. Let s compare the iterative and recursive versions: def factorial_recursive(n): if n == 0 or n == 1: return 1 else: return n * factorial_recursive(n-1) def factorial_iterative(n): total = 1 while n > 1: total = total * n n = n - 1 return total Let s also compare fibonacci. def fib_recursive(n): if n == 0: return 0 elif n == 1: return 1 else: return fib_recursive(n - 1) + fib_recursive(n - 2) def fib_iterative(n): prev, curr = 0, 1 while n > 0: prev, curr = curr, prev + curr n = n - 1 return prev For the recursive version, we copied the definition of the Fibonacci sequence straight into code! The nth Fibonacci number is simply the sum of the two before it. In iteration, you need to keep track of more numbers and have a better understanding of the code. Some code is easier to write iteratively and some recursively. Have fun experimenting with both!

DISCUSSION 3: RECURSION Page 4 1. Our Python interpreter is broken and pow no longer works! However, we can write our own replacement. Let s try writing it both iteratively and recursively. Both expt iter(base, power) and expt rec(base, power) implement the exponent function, so we should get the same answer regardless of which one we use. Assume that power is a non-negative integer. def expt_iter(base, power): Implements the exponent function iteratively >>> expt_iter(2, 3) 8 >>> expt_iter(4, 0) 1 def expt_rec(base, power): Implements the exponent function recursively >>> expt_rec(3, 2) 9

DISCUSSION 3: RECURSION Page 5 3 Tree Recursion Consider a function that requires more than one recursive call. A simple example is the previous function: def fib(n): if n == 0: return 0 elif n == 1: return 1 else: return fib(n - 1) + fib(n - 2) This type of recursion is called tree recursion, because it makes more than one recursive call in its recursive case. If we draw out the recursive calls, we see the recursive calls in the shape of an upside-down tree: fib(4) fib(3) fib(2) fib(2) fib(1) fib(1) fib(0) We could, in theory, use loops to write the same procedure. However, problems that are naturally solved using tree recursive procedures are generally difficult to write iteratively. As a general rule of thumb, whenever you need to try multiple possibilities at the same time, you should consider using tree recursion.

DISCUSSION 3: RECURSION Page 6 1. I want to go up a flight of stairs that has n steps. I can either take 1 or 2 steps each time. How many different ways can I go up this flight of stairs? Write a function count stair ways that solves this problem for me. Assume n is positive. Before we start, what s the base case for this question? What is the simplest input? What do count stair ways(n - 1) and count stair ways(n - 2) represent? Use those two recursive calls to write the recursive case: def count_stair_ways(n): 2. Consider an insect in an M by N grid. The insect starts at the bottom left corner, (0, 0), and wants to end up at the top right corner (M-1, N-1). The insect is only capable of moving right or up. Write a function paths that takes a grid length and width and returns the number of different paths the insect can take from the start to the goal. (There is a closed-form solution to this problem, but try to answer it procedurally using recursion.) def paths(m, n): >>> paths(2, 2) 2 >>> paths(117, 1) 1

DISCUSSION 3: RECURSION Page 7 3. The TAs want to print handouts for their students. However, for some unfathomable reason, both the printers are broken; the first printer only prints multiples of n1, and the second printer only prints multiples of n2. Help the TAs figure out whether or not it is possible to print an exact number of handouts! First try to solve without a helper function. Also try to solve using a helper function and adding up to the sum. def has_sum(total, n1, n2): >>> has_sum(1, 3, 5) False >>> has_sum(5, 3, 5) # 0(3) + 1(5) = 5 True >>> has_sum(11, 3, 5) # 2(3) + 1(5) = 11 True

DISCUSSION 3: RECURSION Page 8 4. The next day, the printers break down even more! Each time they are used, Printer A prints a random x copies 50 x 60, and Printer B prints a random y copies 130 y 140. The TAs also relax their expectations: they are satisfied as long as they get at least lower, but no more than upper, copies printed. (More than upper copies is unacceptable because it wastes too much paper.) Hint: Try using a helper function. def sum_range(lower, upper): >>> sum_range(45, 60) # Printer A prints within this range True >>> sum_range(40, 55) # Printer A can print a number 56-60 False >>> sum_range(170, 201) # Printer A + Printer B will print... # somewhere between 180 and 200 copies total True