What is an algorithm?

Similar documents
Warmup: On paper, write a C++ function that takes a single int argument (n) and returns the product of all the integers between 1 and n.

CSC 148 Lecture 3. Dynamic Typing, Scoping, and Namespaces. Recursion

15-110: Principles of Computing, Spring Problem Set 3 (PS3) Due: Friday, February 9 by 2:30PM on Gradescope

2010Fa CS10 Online Final Answers Section 1

CS 301: Recursion. The Art of Self Reference. Tyler Caraza-Harter

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

CS 1301 CS1 with Robots Summer 2007 Exam 1

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

Recursion. Contents. Steven Zeil. November 25, Recursion 2. 2 Example: Compressing a Picture 4. 3 Example: Calculator 5

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

CMSC 201 Fall 2016 Lab 13 More Recursion

Announcements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop

Structure and Interpretation of Computer Programs Spring 2014 Final (with corrections)

Math 152: Applicable Mathematics and Computing

Data 8 Final Review #1

Phil 320 Chapter 1: Sets, Functions and Enumerability I. Sets Informally: a set is a collection of objects. The objects are called members or

Question 1. tmp = Stack() # Transfer every item from stk onto tmp. while not stk.is_empty(): tmp.push(stk.pop())

UNIT 2B An Introduction to Programming. Announcements

Taking Apart Numbers and Shapes

University of Washington CSE 140 Data Programming Winter Final exam. March 11, 2013

Lecture 26: Sorting CS 1110 Introduction to Computing Using Python

CS201 Discussion 7 MARKOV AND RECURSION

UNIT 2B An Introduction to Programming ( for -loops) Principles of Computing, Carnegie Mellon University

CS 115 Lecture. Boolean logic Taken from notes by Dr. Neil Moore

Only to be used for arranged hours. Order of Operations

While Loops A while loop executes a statement as long as a condition is true while condition: statement(s) Statement may be simple or compound Typical

Introduction to the Java Basics: Control Flow Statements

ECE 2574: Data Structures and Algorithms - Recursion Part I. C. L. Wyatt

3/12/2018. Structures. Programming in C++ Sequential Branching Repeating. Loops (Repetition)

CS 100: Computability, Python Lists

FORM 2 (Please put your name and form # on the scantron!!!!)

Reading 8 : Recursion

Data structure and algorithm in Python

Announcements. Project 5 is on the street. Second part is essay questions for CoS teaming requirements.

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

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

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

QUIZ. 0] Define arrays 1] Define records 2] How are arrays and records: (a) similar? (b) different?

CSCI 136 Data Structures & Advanced Programming. Lecture 14 Fall 2018 Instructor: Bills

Practice problems Set 2

PreCalculus 300. Algebra 2 Review

CMSC 201 Spring 2017 Lab 12 Recursion

Using Scala in CS241

Module 06. Topics: Iterative structure in Python Readings: ThinkP 7. CS116 Spring : Iteration

CSCI 204 Introduction to Computer Science II

CS-141 Exam 2 Review November 10, 2017 Presented by the RIT Computer Science Community

Fall 2017 December 4, Scheme. Instructions

Problem Solving for Intro to Computer Science

Spring 2017 CS 1110/1111 Exam 1

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!

The Citizen s Guide to Dynamic Programming

Recursion. CSCI 112: Programming in C

Chapter 7. Iteration. 7.1 Multiple assignment

TAIL CALLS, ITERATORS, AND GENERATORS 11

Recursive Definitions

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

Module 07: Efficiency

Lecture 6. Register Allocation. I. Introduction. II. Abstraction and the Problem III. Algorithm

CS 151. Recursion (Review!) Wednesday, September 19, 12

Recursion defining an object (or function, algorithm, etc.) in terms of itself. Recursion can be used to define sequences

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

CSCI 101 Midterm Sample Questions

CS 161 Intro to CS I. Finish Pointers/Start Recursion

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

Overview. Factorial Revisited. Iteration via Tail Recursion in Racket. An itera*ve approach to factorial. What is itera*on?

Iteration Part 1. Motivation for iteration. How does a for loop work? Execution model of a for loop. What is Iteration?

CS1110. Lecture 6: Function calls

SECTION 5.1. Sequences

EXAM PREPARATION SECTION 1

CCBC Math 081 Order of Operations Section 1.7. Step 2: Exponents and Roots Simplify any numbers being raised to a power and any numbers under the

Visualize ComplexCities

APCS Semester #1 Final Exam Practice Problems

This homework has an opportunity for substantial extra credit, which is described at the end of this document.

Register allocation. CS Compiler Design. Liveness analysis. Register allocation. Liveness analysis and Register allocation. V.

Programming Studio #9 ECE 190

Knowledge: This lab will help you become familiar with the following content knowledge:

Phys Techniques of Radio Astronomy Part 1: Python Programming LECTURE 2

CS536 Spring 2011 FINAL ID: Page 2 of 11

CS Lecture 19: Loop invariants

61A Lecture 4. Monday, September 9

10/9/17. Using recursion to define objects. CS 220: Discrete Structures and their Applications

Problem Tutorial: Alternating Serves

61A LECTURE 8 SEQUENCES, ITERABLES

61A LECTURE 8 SEQUENCES, ITERABLES. Steven Tang and Eric Tzeng July 8, 2013

CS 1110, LAB 3: STRINGS; TESTING

CS159. Nathan Sprague. November 9, 2015

Conditionals & Control Flow

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

Solutions to Problem Set 1

MEIN 50010: Python Recursive Functions

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

University of Washington CSE 140 Data Programming Winter Final exam. March 11, 2013

CS150 - Sample Final

What is an algorithm?

COMP 202 Recursion. CONTENTS: Recursion. COMP Recursion 1

Today. CISC101 Reminders & Notes. Searching in Python - Cont. Searching in Python. From last time

HOW TO DIVIDE: MCC6.NS.2 Fluently divide multi-digit numbers using the standard algorithm. WORD DEFINITION IN YOUR WORDS EXAMPLE

Theory of control structures

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

Fun facts about recursion

Transcription:

Announcements CS 142 Recursion Reminder: Program 3 due 2/18 by 11:55pm 2 Write a function that computes the factorial of a number using a loop (for or while loop is fine). Examples: factorial(5) returns 120 #(1*2*3*4*5) factorial(8) returns 40320 #(1*2*3*4*5*6*7*8) A different view of the same problem Notice that each product involves computing the entire product on the row above. 3 4 1

5 6 Let s reformulate the definition of a factorial to take advantage of this relationship. 7 8 2

Recursion Recursive Functions A recursive function is a function that calls itself. Recursive functions are used to solve problems where the solution to a problem involves solving a smaller version of the same problem. 2 parts: Base Case: How to solve the smallest version of the problem that we care about. Recursive Case: How to reduce the bigger version of the problem to a smaller version. In order to work, the recursive case (when applied over and over) must eventually reduce every size of the problem down to the base case. What are these 2 parts for factorial? 9 10 How does recursion work? Recursion works (in all modern programming languages) because: All variables are local The stack makes new memory for local variables every time a function is called Let s look at the stack when we call fact(5). 11 12 3

Why is recursion useful? How to get recursion Any loop (for/while) can be replaced with a recursive function that does the same thing. Some languages don t include loops! Because we started with Python and are moving onto C++, we naturally see things in terms of loops. Some problems have a naturally recursive solution that is hard to solve with a loop. Other problems have solutions that work equally well recursively or with loops (iteratively). Forget all loops To find the base case: An instance of a problem is a single occurrence of that problem. What s the smallest version of this problem I would ever care about solving? To find the recursive case: If I have an instance of the problem, how can I phrase how to solve the problem in terms of a smaller instance? 13 14 Trust the recursion Base case is usually easy (When do I stop?) In recursive case: Break the problem into two parts (not necessarily the same size): A part I can solve now. The answer from a smaller instance of the problem. Assume the recursive call does the right thing. Figure out how to combine the two parts. 3 Laws of Recursion A recursive algorithm must have a base case. A recursive algorithm must change its state and move toward the base case. A recursive algorithm must call itself, recursively. 15 16 4

Another Example Sum of a List of Numbers Write a recursive function to compute the sum of a list of numbers. Iterative Solution: def listsum(numlist): thesum = 0 for i in numlist: thesum = thesum + i return thesum We could rewrite the list as a fully parenthesized expression ((((1+3)+5)+7)+9) We can also parenthesize the expression the other way around, (1+(3+(5+(7+9)))) Notice that the innermost set of parentheses, (7+9), is a problem that we can solve without a loop or any special constructs. total= (1+(3+(5+(7+9)))) total= (1+(3+(5+16))) total= (1+(3+21)) total= (1+24) total= 25 Let s restate the sum problem in terms of Python lists. The sum of the list numlist is the sum of the first element of the list (numlist[0]), and the sum of the numbers in the rest of the list (numlist[1:]). listsum(numlist)=first(numlist)+listsum(rest(numlist)) So, what s our base case? 17 18 Sum of a List of Numbers Practice Write a recursive function to compute a^b (a raised to the b power) where a and b are both positive integers. To solve this recursively, solve the recursive case and the base case. Assume there are no built-in functions that will do this operation. Examples: power_to(4, 3) returns 64 power_to(3, 5) returns 243 Series of Recursive Calls Adding a List of Numbers Series of Recursive Returns from Adding a List of Numbers 19 20 5