ENVIRONMENT DIAGRAMS AND RECURSION 2

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

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

ENVIRONMENT DIAGRAMS AND RECURSION 2

HIGHER ORDER FUNCTIONS AND ENVIRONMENT DIAGRAMS 2

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

RECURSION: n. SEE RECURSION 3

HIGHER-ORDER FUNCTIONS 2

RECURSION, RECURSION, (TREE) RECURSION! 3

RECURSION, RECURSION, (TREE) RECURSION! 2

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

RECURSION, RECURSION, (TREE) RECURSION! 3

ITERATION AND RECURSION 3

CONTROL AND HIGHER ORDER FUNCTIONS 1

RECURSION AND LINKED LISTS 3

CONTROL AND HIGHER ORDER FUNCTIONS 2

Lecture #5: Higher-Order Functions. A Simple Recursion. Avoiding Recalculation. Redundant Calculation. Tail Recursion and Repetition

CS1 Lecture 15 Feb. 19, 2018

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

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

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

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

Module 05: Types of recursion

CS116 - Module 5 - Accumulative Recursion

DM502 Programming A. Peter Schneider-Kamp.

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

CS1 Lecture 15 Feb. 18, 2019

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

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

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

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

DRAWING ENVIRONMENT DIAGRAMS

Structure and Interpretation of Computer Programs

DM550/DM857 Introduction to Programming. Peter Schneider-Kamp

61A Lecture 4. Monday, September 9

Measuring Efficiency

functional programming in Python, part 2

Exercise 1 ( = 24 points)

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

Structure and Interpretation of Computer Programs Fall 2015 Midterm 1

Midterm 1 Review Fall 2017 September 8, Functions. Instructions

6.00 Notes On Big-O Notation

TAIL RECURSION, SCOPE, AND PROJECT 4 11

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

Recursion CS GMU

Reading 8 : Recursion

recursive algorithms 1

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

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

Encodings. Using the minimal λ-calculus language we get. functions. local binding. booleans. numbers... and recursive functions?

Recursive Definitions

DM536 Introduction to Programming. Peter Schneider-Kamp.

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

CS2500 Exam 2 Fall 2011

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

CSCI 121: Recursive Functions & Procedures

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

Midterm Review. CS61A Summer Katya Stukalova Jerome Baek

Koch snowflake. Fractal Fern

CS1 Recitation. Week 2

UNIT 5A Recursion: Basics. Recursion

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

Introduction to Scientific Computing

Exercise 1 ( = 18 points)

1.3. Conditional expressions To express case distinctions like

INTERPRETERS AND TAIL CALLS 9

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

Class 6: Efficiency in Scheme

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

61A Lecture 7. Monday, September 16

Compiler Construction Lecture 05 A Simple Stack Machine. Lent Term, Lecturer: Timothy G. Griffin. Computer Laboratory University of Cambridge

61A Lecture 6. Monday, February 2

An introduction to Scheme

SCHEME AND CALCULATOR 5b

61A Lecture 7. Monday, September 15

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs Spring 2017 Mock Midterm 1

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

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

UNIT 5A Recursion: Basics. Recursion

CS61A Notes Disc 11: Streams Streaming Along

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

Structure and Interpretation of Computer Programs

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

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

Sample Final Exam Questions

Algorithm Design and Recursion. Search and Sort Algorithms

CS61A Summer 2010 George Wang, Jonathan Kotker, Seshadri Mahalingam, Eric Tzeng, Steven Tang

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

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

Structure and Interpretation of Computer Programs

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

Introduction to Concepts in Functional Programming. CS16: Introduction to Data Structures & Algorithms Spring 2017

PROGRAMMING IN HASKELL. CS Chapter 6 - Recursive Functions

Functions and Recursion

More Complicated Recursion CMPSC 122

MORE SCHEME. 1 What Would Scheme Print? COMPUTER SCIENCE MENTORS 61A. October 30 to November 3, Solution: Solutions begin on the following page.

EECE.3170: Microprocessor Systems Design I Summer 2017 Homework 4 Solution

Fruitful Recursion (recursion that returns a value)

STREAMS, ITERATORS, AND BINARY TREES 10

Transcription:

ENVIRONMENT DIAGRAMS AND RECURSION 2 COMPUTER SCIENCE 61A September 8, 2016 1 More Environment Diagrams Recall that an environment diagram keeps track of all the variables that have been defined and the values they are bound to. However, values are not necessarily only integers and strings. Environment diagrams can model more complex programs that utilize higher order functions. def add_num(x): return lambda y: x + y add_two = add_num(2) add_two(3) Lambdas are represented similiarly to functions in environment diagrams, but since they lack instrinsic names, the lambda symbol (λ) is used instead.

DISCUSSION 2: ENVIRONMENT DIAGRAMS AND RECURSION Page 2 The parent of any function (including lambdas) is always the frame in which the function is defined. It is useful to include the parent in environment diagrams in order to find variables that are not defined in the current frame. In the previous example, when we call add two (which is really the lambda function), we need to know what x is in order to compute x + y. Since x is not in the frame f2, we look at the frame s parent, which is f1. There, we find x is bound to 2. As illustrated above, higher order functions that return a function have their return value represented with a pointer to the function object. 1. Draw the environment diagram that results from executing the code below. from operator import add six = 1 def ty(one, a): fall = one(a, six) return fall six = ty(add, 6) fall = ty(add, 6)

DISCUSSION 2: ENVIRONMENT DIAGRAMS AND RECURSION Page 3 2. Draw the environment diagram for the following code: def curry2(h): def f(x): def g(y): return h(x, y) return g return f make_adder = curry2(lambda x, y: x + y) add_three = make_adder(3) five = add_three(2)

DISCUSSION 2: ENVIRONMENT DIAGRAMS AND RECURSION Page 4 3. Draw the environment diagram that results from running the following code: n = 7 def f(x): n = 8 return x + 1 def g(x): n = 9 def h(): return x + 1 return h def f(f, x): return f(x + n) f = f(g, n) g = (lambda y: y())(f)

DISCUSSION 2: ENVIRONMENT DIAGRAMS AND RECURSION Page 5 4. The following question is extremely difficult. Something like this would not appear on the exam. Nonetheless, it s a fun problem to try. Draw the environment diagram for the following code: (Note that using the + operator with two strings results in the second string being appended to the first. For example "C" + "S" concatenates the two strings into one string "CS") y = "y" h = y def y(y): h = "h" if y == h: return y + "i" y = lambda y: y(h) return lambda h: y(h) y = y(y)(y)

DISCUSSION 2: ENVIRONMENT DIAGRAMS AND RECURSION Page 6 2 Recursion 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) 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. 2.1 Questions 1. Write a function multiply(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 multiply? For the recursive case, what does calling multiply(m - 1, n) do? What does calling multiply(m, n - 1) do? Do we prefer one over the other?

DISCUSSION 2: ENVIRONMENT DIAGRAMS AND RECURSION Page 7 def multiply(m, n): >>> multiply(5, 3) 15 2. 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

DISCUSSION 2: ENVIRONMENT DIAGRAMS AND RECURSION Page 8 3. Is there an easy way to change countdown to count up instead? 4. 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 2: ENVIRONMENT DIAGRAMS AND RECURSION Page 9 3 Tree Recursion Consider a function that requires more than one recursive call. A simple example is the previous recursive fibonacci 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 2: ENVIRONMENT DIAGRAMS AND RECURSION Page 10 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 a special version of the count stairways problem, where instead of taking 1 or 2 steps, we are able to take up to and including k steps at a time. Write a function count k that figures out the number of paths for this scenario. def count_k(n, k): >>> count_k(3, 3) # 3, 2 + 1, 1 + 2, 1 + 1 + 1 4 >>> count_k(4, 4) 8 >>> count_k(10, 3) 274 >>> count_k(300, 1) # Only one step at a time 1