RECURSION: n. SEE RECURSION 3

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

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

RECURSION, RECURSION, (TREE) RECURSION! 3

ENVIRONMENT DIAGRAMS AND RECURSION 2

RECURSION, RECURSION, (TREE) RECURSION! 3

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

ITERATION AND RECURSION 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

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

RECURSION AND LINKED LISTS 3

61A Lecture 6. Monday, February 2

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

Problem Set CVO 103, Spring 2018

Functions and Recursion

Structured programming

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

DM502 Programming A. Peter Schneider-Kamp.

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

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

DM536 Introduction to Programming. Peter Schneider-Kamp.

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

DM550/DM857 Introduction to Programming. Peter Schneider-Kamp

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

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

COMP 202 Recursion. CONTENTS: Recursion. COMP Recursion 1

61A Lecture 7. Monday, September 16

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

CSE 230 Intermediate Programming in C and C++ Recursion

61A Lecture 7. Monday, September 15

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

UNIT 5A Recursion: Basics. Recursion

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

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

Module 05: Types of recursion

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

functional programming in Python, part 2

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

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

Midterm Review. CS61A Summer Katya Stukalova Jerome Baek

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

DM536 Introduction to Programming. Peter Schneider-Kamp.

A function that invokes itself is said to

CONTROL AND HIGHER ORDER FUNCTIONS 1

Case by Case. Chapter 3

SCHEME AND CALCULATOR 5b

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

CS116 - Module 5 - Accumulative Recursion

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

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

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

EXPRESSIONS, STATEMENTS, AND FUNCTIONS 1

EE 368. Weeks 4 (Notes)

DM502 Programming A. Peter Schneider-Kamp.

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

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

Recursion. Chapter 11. Chapter 11 1

Recursion CS GMU

Python lab session 1

RACKET BASICS, ORDER OF EVALUATION, RECURSION 1

Creating a new data type

INTERPRETERS AND TAIL CALLS 9

CONTROL AND HIGHER ORDER FUNCTIONS 2

Streams and Evalutation Strategies

11/2/2017 RECURSION. Chapter 5. Recursive Thinking. Section 5.1

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)

Names and Functions. Chapter 2

Fundamentals of Programming Session 13

Ch.5. Loops. (a.k.a. repetition or iteration)

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

TAIL CALLS, ITERATORS, AND GENERATORS 11

CSI 32. Lecture 15. Chapter 11 Recursion Functional Recursion 11.4 Binary Search

TUPLES AND RECURSIVE LISTS 5

CS 61A Control and Environments Spring 2018 Discussion 1: January 24, Control. If statements. Boolean Operators

Control and Environments Fall 2017 Discussion 1: August 30, Control. If statements. Boolean Operators

CONTROL AND ENVIRONMENTS 1

Algorithm Design and Recursion. Search and Sort Algorithms

List Functions, and Higher-Order Functions

Conditionals and Recursion. Python Part 4

Functionally Modular. Self-Review Questions

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

6.001 Notes: Section 4.1

HIGHER ORDER FUNCTIONS 2

Recursive Definitions

A library of recursive functions

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

CSCI 121: Recursive Functions & Procedures

Loops / Repetition Statements

Koch snowflake. Fractal Fern

C ONTROL AND H IGHER O RDER F UNCTIONS

Structure and Interpretation of Computer Programs

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

Problem Solving for Intro to Computer Science

University of Massachusetts Lowell

1. Let n be a positive number. a. When we divide a decimal number, n, by 10, how are the numeral and the quotient related?

Transcription:

RECURSION: n. SEE RECURSION 3 COMPUTER SCIENCE 61A June 30, 2015 1 Recursion A recursive function is a function that calls itself. Below is a recursive factorial function. def factorial(n): if n == 0 or n == 1: else: return n * factorial(n-1) 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 your 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. 1

DISCUSSION 3: RECURSION: n. SEE RECURSION Page 2 1.1 Cool recursion questions! 1. Print out a countdown using recursion. def countdown(n): >>> countdown(3) 3 2 1 First, think about a base case. 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. 2. Is there an easy way to change countdown to count up instead? 3. Write a function recursive mul(m, n) that multiplies two numbers m and n. Assume m and n are positive integers. Use recursion, not mul or *! Hint: 5*3 = 5 + 5*2 = 5 + 5 + 5*1. For the base case, what is the simplest possible input for recursive mul? For the recursive case, what does calling multiply(m - 1, n) do? What does calling multiply(m, n - 1) do? Which one do we want to use?

DISCUSSION 3: RECURSION: n. SEE RECURSION Page 3 def multiply(m, n): >>> multiply(5, 3) 15 4. 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 a non-negative integer. Use recursion, not pow! def expt(base, power): 5. Write a recursive function that sums the digits of a number n. Assume n is positive. You might find the operators // and % useful. def sum_digits(n): >>> sum_digits(7) 7 >>> sum_digits(30) 3 >>> sum_digits(228) 12

DISCUSSION 3: RECURSION: n. SEE RECURSION Page 4 6. Below is the iterative version of is prime, which returns True if positive integer n is a prime number and False otherwise: def is_prime(n): if n == 1: return False k = 2 while k < n: if n % k == 0: return False k += 1 return True Implement the recursive is prime function. Do not use a while loop, use recursion. def is_prime(n): 7. Write sum primes up to(n), which sums up every prime up to and including n. Assume you have an is prime(n) predicate. def sum_primes_up_to(n):

DISCUSSION 3: RECURSION: n. SEE RECURSION Page 5 1.2 Recursive Environment Diagram! 1. 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 3: RECURSION: n. SEE RECURSION Page 6 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: 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, while the recursive function works until n is less than or equal to 0, the iterative function works while n is greater than 0. They re essentially the same. Let s also compare fibonacci. def fib_recursive(n): if n == 0: return 0 elif n == 1: else: return fib_recursive(n - 1) + fib_recursive(n - 2) def fib_iterative(n): current, next = 0, 1 while n > 0: current, next = next, current + next n = n - 1 return current 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. Iteratively, 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!