RECURSION, RECURSION, (TREE) RECURSION! 2

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

RECURSION, RECURSION, (TREE) RECURSION! 3

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

ITERATION AND RECURSION 3

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

RECURSION: n. SEE RECURSION 3

ENVIRONMENT DIAGRAMS AND RECURSION 2

RECURSION AND LINKED LISTS 3

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

ENVIRONMENT DIAGRAMS AND RECURSION 2

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

Module 05: Types of recursion

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

CS1 Recitation. Week 2

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

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

UNIT 5A Recursion: Basics. Recursion

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

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

RACKET BASICS, ORDER OF EVALUATION, RECURSION 1

CS116 - Module 5 - Accumulative Recursion

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

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

Algorithm Design and Recursion. Search and Sort Algorithms

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

TAIL RECURSION, SCOPE, AND PROJECT 4 11

CS1 Lecture 15 Feb. 19, 2018

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

Problem Set CVO 103, Spring 2018

Resources matter. Orders of Growth of Processes. R(n)= (n 2 ) Orders of growth of processes. Partial trace for (ifact 4) Partial trace for (fact 4)

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

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

CSCI 121: Recursive Functions & Procedures

SCHEME AND CALCULATOR 5b

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

DM550/DM857 Introduction to Programming. Peter Schneider-Kamp

15-122: Principles of Imperative Computation, Fall 2015

DM536 Introduction to Programming. Peter Schneider-Kamp.

More Complicated Recursion CMPSC 122

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

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

Claremont McKenna College Computer Science

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

DM502 Programming A. Peter Schneider-Kamp.

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

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

TAIL CALLS, ITERATORS, AND GENERATORS 11

6.001 Notes: Section 4.1

Koch snowflake. Fractal Fern

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

I2204 ImperativeProgramming Semester: 1 Academic Year: 2018/2019 Credits: 5 Dr Antoun Yaacoub

Lecture Notes, CSE 232, Fall 2014 Semester

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

6.01, Spring Semester, 2008 Assignment 3, Issued: Tuesday, February 19 1

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

CSE 230 Intermediate Programming in C and C++ Recursion

CSI33 Data Structures

Reading 8 : Recursion

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

Programming for Engineers in Python

Homework. Reading: Chapter 17 Homework: All exercises from Chapter 17 Due: 10/27 Correction: Chapter 16 homework is due 10/25

CS61A Notes Week 1A: Basics, order of evaluation, special forms, recursion

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

CSC236 Week 4. Larry Zhang

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

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

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

University of Massachusetts Lowell

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

Lecture 6 CS2110 Spring 2013 RECURSION

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

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

CIS 194: Homework 6. Due Monday, February 25. Fibonacci numbers

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!

CS1 Lecture 15 Feb. 18, 2019

Conditionals: Making Choices

Functions and Recursion

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

CS103 Handout 29 Winter 2018 February 9, 2018 Inductive Proofwriting Checklist

Forward recursion. CS 321 Programming Languages. Functions calls and the stack. Functions calls and the stack

Table of Laplace Transforms

Solutions to CS 61A Challenge Problems: Midpoint Review

The transition: Each student passes half his store of candies to the right. students with an odd number of candies eat one.

where each number (after the first two 1 s) is the sum of the previous two numbers.

Hints for Exercise 4: Recursion

Programming with Python

CSE 143 Lecture 10. Recursion

CSE200 Lecture 6: RECURSION

RECURSION. Problem Solving with Computers-II 6

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

Functionally Modular. Self-Review Questions

PIETRO, GIORGIO & MAX ROUNDING ESTIMATING, FACTOR TREES & STANDARD FORM

Problem Solving for Intro to Computer Science

How invariants help writing loops Author: Sander Kooijmans Document version: 1.0

CS1 Lecture 5 Jan. 25, 2019

Recursive Definitions

Drawing Hands, by M. C. Escher (lithograph, 1948)

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

Notes - Recursion. A geeky definition of recursion is as follows: Recursion see Recursion.

Transcription:

RECURSION, RECURSION, (TREE) RECURSION! 2 COMPUTER SCIENCE 61A February 5, 2015 A function is recursive if it calls itself. Below is a recursive factorial function. def factorial(n): if n == 0 or n == 1: else: return n * factorial(n-1) 1 Recursion It seems like this won t work we haven t finished defining factorial, yet we re already calling it. However, we do have one base case: when n is 0 or 1. Now we can compute factorial(1) in terms of factorial(0), and factorial(2) in terms of factorial(1), and factorial(3) 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? The answer should be simple, and is often given by definition. For example, factorial(0) is 1 by definition. The first two Fibonacci numbers are 0 and 1. 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 as you use more recursion, you will get more used to this idea. For factorial, we make the recursive call factorial(n-1) this is the recursive breakdown. 3. Use your recursive call to solve the full problem: Remember that we are assuming your recursive call just 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. 1

DISCUSSION 2: RECURSION, RECURSION, (TREE) RECURSION! Page 2 1.1 Cool Questions! 1. Print out a countdown using recursion. def countdown(n): >>> countdown(3) 3 2 1 2. Is there an easy way to change countdown to count up instead? 3. Write a procedure expt(base, power), which implements the exponent function. For example, expt(3, 2) returns 9, and expt(2, 3) returns 8. Assume power is always an integer. Use recursion, not pow! def expt(base, power):

DISCUSSION 2: RECURSION, RECURSION, (TREE) RECURSION! Page 3 4. Fill in the is prime function, which returns True if n is a prime number and False otherwise. Hint: We wrote this iteratively last week, but this time use recursion! def is_prime(n): 5. Write sum primes up to(n), which sums up every prime up to and including n. Assume you have an is prime() predicate. def sum_primes_up_to(n):

DISCUSSION 2: RECURSION, RECURSION, (TREE) RECURSION! Page 4 6. Draw an environment diagram for the following code: def rec(x, y): if y > 0: return x * rec(x, y - 1) rec(3, 2) Bonus question: what does this function do?

DISCUSSION 2: RECURSION, RECURSION, (TREE) RECURSION! Page 5 2 Tree Recursion Consider a function that requires more than one recursive call. A simple example is a function that computes Fibonacci numbers: def fib(n): if n == 0: return 0 elif n == 1: else: return fib(n - 1) + fib(n - 2) This is where recursion really begins to shine: it allows us to explore two different calculations at the same time. In this case, we are exploring two different possibilities (or paths): the n 1 case and the n 2 case. With the power of recursion, exploring all possibilities like this is very straightforward. You simply try everything using recursive calls for each case, then combine the answers you get back. This type of recursion is called tree recursion, because the different branches of computation that form from this recursion end up looking like an upside-down tree: fib(4) fib(3) fib(2) fib(2) fib(1) 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, and require the use of additional data structures to hold information. As a general rule of thumb, whenever you need to try multiple possibilities at the same time, you should consider using tree recursion.

DISCUSSION 2: RECURSION, RECURSION, (TREE) RECURSION! Page 6 2.1 Exercises 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. def count_stair_ways(n): 2. Pascal s triangle is a useful recursive definition that tells us the coefficients in the expansion of the polynomial (x + a) n. Each element in the triangle has a coordinate, given by the row it is on and its position in the row (which you could call its column). Every number in Pascal s triangle is defined as the sum of the item above it and the item that is directly to the upper left of it. If there is a position that does not have an entry, we treat it as if we had a 0 there. Below are the first few rows of the triangle: Item: 0 1 2 3 4 5 Row 0: 1 Row 1: 1 1 Row 2: 1 2 1 Row 3: 1 3 3 1 Row 4: 1 4 6 4 1 Row 5: 1 5 10 10 5 1... Define the procedure pascal(row, column) which takes a row and a column, and finds the value at that position in the triangle. Don t use the closed-form solution, if you know it. def pascal(row, column):

DISCUSSION 2: RECURSION, RECURSION, (TREE) 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(sum, n1, n2): >>> has_sum(1, 3, 5) False >>> has_sum(5, 3, 5) # 1(5) + 0(3) = 5 True >>> has_sum(11, 3, 5) # 2(3) + 1(5) = 11 True

DISCUSSION 2: RECURSION, RECURSION, (TREE) RECURSION! Page 8 2.2 Extra Questions 1. 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 ;... # the TAs would be satisfied with any number it prints... True >>> sum_range(40, 55) # Printer A can print some number 56-60... # copies, which is not within the TA acceptable range... False >>> sum_range(170, 201) # Printer A + Printer B will print... # somewhere between 180 and 200 copies total... True

DISCUSSION 2: RECURSION, RECURSION, (TREE) RECURSION! Page 9 3 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: else: return n * factorial_recursive(n-1) def factorial_iterative(n): total = 1 while n > 1: total = total * n n = n - 1 return total Notice that the recursive test corresponds to the iterative test. While the recursive function works until n is less than or equal to 0, the iterative works while n is greater than 0. They are essentially the same. Let s also compare fibonacci. def fib_r(n): if n == 0: return 0 elif n == 1: else: return fib_r(n - 1) + fib_r(n - 2) def fib_i(n): curr, next = 0, 1 while n > 0: curr, next = next, curr + next n = n - 1 return curr For the recursive version, we copied the definition of the Fibonacci sequence straight into code! The nth fibonacci number is literally the sum of the two before it. Iteratively, you need to keep track of more numbers and have a better understanding of the code. Sometimes code is easier to write iteratively. Sometimes code is easier to write recursively. Have fun experimenting with both!