Lecture #7: Recursion (and a data structure)

Similar documents
Lecture #6: Higher-Order Functions at Work

Lecture #10: Sequences. Last modified: Mon Feb 22 16:33: CS61A: Lecture #10 1

1KOd17RMoURxjn2 CSE 20 DISCRETE MATH Fall

CS 61A HKN Review Session. Nathan Zhang, Caleb Wyllie

Structure and Interpretation of Computer Programs Spring 2017 Mock Midterm 1

CMSC 201 Computer Science I for Majors

Welcome to CS61A! Last modified: Thu Jan 23 03:58: CS61A: Lecture #1 1

The Pyth Language. Administrivia

CMSC201 Computer Science I for Majors

Midterm Review. CS61A Summer Katya Stukalova Jerome Baek

INTERMEDIATE LEVEL PYTHON PROGRAMMING SELECTION AND CONDITIONALS V1.0

TUPLES AND RECURSIVE LISTS 5

PREPARING FOR PRELIM 1

Lecture #21: Search Trees, Sets. Last modified: Tue Mar 18 18:15: CS61A: Lecture #21 1

CS61A Lecture 9 Immutable Data Structures. Jom Magrotker UC Berkeley EECS July 2, 2012

Defining Functions. CSc 372. Comparative Programming Languages. 5 : Haskell Function Definitions. Department of Computer Science University of Arizona

61A Lecture 7. Monday, September 16

Recursive definition of sets and structural induction

CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output

Lecture #11: Immutable and Mutable Data. Last modified: Sun Feb 19 17:03: CS61A: Lecture #11 1

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

Lecture #16: Generic Functions and Expressivity. Last modified: Fri Feb 26 19:16: CS61A: Lecture #16 1

Programming Languages and Techniques (CIS120)

PIC 16, Fall Variables, Dynamically-typed, Mutable, Immutable, Functions. Michael Andrews. October 1, Department of Mathematics UCLA

This was the second midterm from I have added a few comments in bold type, like this.

Practical Questions CSCA48 Week 6

Lecture #15: Generic Functions and Expressivity. Last modified: Wed Mar 1 15:51: CS61A: Lecture #16 1

Lecture #12: Mutable Data. Last modified: Sun Feb 19 17:15: CS61A: Lecture #12 1

Selection statements. CSE 1310 Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington

EXPRESSIONS, STATEMENTS, AND FUNCTIONS 1

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Lecture #12: Mutable Data. map rlist Illustrated (III) map rlist Illustrated. Using Mutability For Construction: map rlist Revisited

Which of the following expressions has the type int list?

Beyond Blocks: Python Session #1

To figure this out we need a more precise understanding of how ML works

Conditionals & Control Flow

Artificial Intelligence Lecture 1

CSCE 110: Programming I

CS61A Lecture 15. Amir Kamil UC Berkeley February 25, 2013

Lecture 8: Conditionals & Control Flow (Sections ) CS 1110 Introduction to Computing Using Python

CMSC201 Computer Science I for Majors

Lecture 16: Static Semantics Overview 1

61A LECTURE 15 MEMOIZATION, RECURSIVE DATA, SETS

To prove something about all Boolean expressions, we will need the following induction principle: Axiom 7.1 (Induction over Boolean expressions):

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

CS152: Programming Languages. Lecture 2 Syntax. Dan Grossman Spring 2011

Announcements. Lab 11 is due tomorrow. Quiz 6 is on Monday. Ninja session tonight, 7-9pm. The final is in two weeks!

A lot of people make repeated mistakes of not calling their functions and getting errors. Make sure you're calling your functions.

4. Write the output that would be printed from each of the following code fragments. (8pts) x = 9 y = x / 2 print('y ==', y) +1 4.

Lecture #23: Conversion and Type Inference

Conversion vs. Subtyping. Lecture #23: Conversion and Type Inference. Integer Conversions. Conversions: Implicit vs. Explicit. Object x = "Hello";

Control Structures 1 / 17

CMSC201 Computer Science I for Majors

CSE 115. Introduction to Computer Science I

Python I. Some material adapted from Upenn cmpe391 slides and other sources

HW 1 CMSC 452. Morally DUE Feb 7 NOTE- THIS HW IS THREE PAGES LONG!!! SOLUTIONS THROUGOUT THIS HW YOU CAN ASSUME:

CS108 Lecture 19: The Python DBAPI

Student Number: Comments are not required except where indicated, although they may help us mark your answers.

Text Input and Conditionals

CS61A Lecture 16. Amir Kamil UC Berkeley February 27, 2013

Lecture 8. Conditionals & Control Flow

CS 1110: Introduction to Computing Using Python Lists and Sequences

Iteration and For Loops

61A LECTURE 8 SEQUENCES, ITERABLES

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

Induction and Semantics in Dafny

CS Summer 2013

Visualize ComplexCities

Lecture 3. Input, Output and Data Types

Lecture #13: More Sequences and Strings. Last modified: Tue Mar 18 16:17: CS61A: Lecture #13 1

CS61A Lecture 16. Amir Kamil UC Berkeley February 27, 2013

Introduction to Python (All the Basic Stuff)

Comp 150 Exam 2 Overview.

ENGR 101 Engineering Design Workshop

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

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

Syntax-Directed Translation. Lecture 14

Python Evaluation Rules

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

Announcements. Project 2 due next Monday. Next Tuesday is review session; Midterm 1 on Wed., EE 129, 8:00 9:30pm

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

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

Teaching London Computing

Python: common syntax

CS70 - Lecture 6. Graphs: Coloring; Special Graphs. 1. Review of L5 2. Planar Five Color Theorem 3. Special Graphs:

Programming Languages and Techniques (CIS120)

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

CS61A Lecture 20 Object Oriented Programming: Implementation. Jom Magrotker UC Berkeley EECS July 23, 2012

learning objectives learn about variables, their types and their values learn about different number representations

Public-Service Announcement

Lecture #13: Type Inference and Unification. Typing In the Language ML. Type Inference. Doing Type Inference

CSCE 110 Programming I


Turn in a printout of your code exercises stapled to your answers to the written exercises at 2:10 PM on Thursday, January 13th.

Fundamentals of Programming. Lecture 1: Introduction + Basic Building Blocks of Programming

DM536 Introduction to Programming. Peter Schneider-Kamp.

SCHEME AND CALCULATOR 5b

CircuitPython 101: Working with Lists, Iterators and Generators

Programming Languages and Techniques (CIS120)

Transcription:

Lecture #7: Recursion (and a data structure) Announcements: A message from the AWE: The Association of Women in EECS is hosting a 61A party this Sunday (2/9) from 1 3PM in the Woz! Come hang out, befriend other girls in 61A and meet AWE members who have taken it before! There will be lots of food, games, and fun! Guerrilla Sections this weekend. Extra, optional sections to practice HOF and Environment Diagrams this weekend. You ll be expected to work in groups on questions that range from basic to midterm-level. Details will be announced on Piazza. Last modified: Thu Feb 20 20:10:46 2014 CS61A: Lecture #7 1

Data Structures To date, we ve dealt with numbers and functions for the most part. Although one can do just about anything with these, it s not exactly convenient. Example: encode a pair of integers as a single integer: (x,y) 2 x 3 y Every (x,y) pair can be encoded, but extracting x and y is a chore. So Python (like most languages) provides a set of additional data structures for representing collections of values. Last modified: Thu Feb 20 20:10:46 2014 CS61A: Lecture #7 2

Creating Tuples To create (construct) a tuple, use a sequence of expressions in parentheses: () # The tuple with no values (1, 2) # A pair: tuple with two items (1, ) # A singleton tuple: use comma to distinguish from (1). (1, "Hello", (3, 4)) # Any mix of values possible. When unambiguous, the parentheses are unnecessary: x = 1, 2, 3 # Same as x = (1,2,3) return True, 5 # Same as return (True, 5) for i in 1, 2, 3: # Same as for i in (1,2,3): Last modified: Thu Feb 20 20:10:46 2014 CS61A: Lecture #7 3

Selecting from Tuples Can compare, print, or select values from a tuple; little else. Selection is by explicit item number or unpacking : >>> x = (1, 7, 5) >>> print(x[1], x[2]) 7 5 >>> from operator import getitem >>> print(getitem(x, 1), getitem(x, 2)) 7 5 >>> x = (1, (2, 3), 5) >>> print(len(x)) 3 >>> a, b, c = x >>> print(b, c) (2, 3) 5 >>> d, (e, f), g = x >>> print(e, g) 2, 5 >>> x, y = y, x??? Last modified: Thu Feb 20 20:10:46 2014 CS61A: Lecture #7 4

More Selection Selecting subtuples (slices) is also possible: >>> x = (1, 7, 5, 6) >>> print(x[1:3], x[0:2], x[:2], x[1:4], x[1:], x[1:2]) (7, 5) (1, 7) (1, 7) (7, 5, 6) (7, 5, 6) (7,) >>> from operator import getitem >>> print(getitem(x, slice(1,3)), getitem(x, slice(0,2)) (7, 5) (1, 7) >>> a, *b, c = x >>> print(a, b, c) 1 (7, 5) 6 >>> a, *b = x >>> print(a, b) 1 (7, 5, 6) Last modified: Thu Feb 20 20:10:46 2014 CS61A: Lecture #7 5

Multiple Returns Tuples provide a useful way to return multiple things from a function: >>> divmod(38, 5) # Returns (38//5, 38%5) (7, 3) >>> def sumprod(x, y):... return x+y, x*y >>> sumprod(3, 5) (8, 15) Last modified: Thu Feb 20 20:10:46 2014 CS61A: Lecture #7 6

Tuple is one type of value. Tuple is a Recursive Type Values thus include integers, booleans, strings, and tuples (among others). Tuples are sequences of 0 or more values. Therefore, the definitions of value and tuple are is recursive: they refer to themselves. In this case, we d say that their definitions are mutually recursive, since they each refers to the other. Recursive data types and recursive algorithms go together. Last modified: Thu Feb 20 20:10:46 2014 CS61A: Lecture #7 7

Example: How Many Numbers? Let s consider a restricted tuple (call it a numeric pair ) consisting of: The empty tuple: (), Or a tuple containing two values, each of which is an integer or a numeric pair (still more recursion!) Given such a numeric pair, how many numbers are in it? Last modified: Thu Feb 20 20:10:46 2014 CS61A: Lecture #7 8

Example: Code def count_vals(pair): """Assuming PAIR is a numeric pair, the total number of integers contained in the pair. >>> count_vals(()) 0 >>> count_vals( (1, ()) ) 1 >>> count_vals( (1, 2) ) 2 >>> count_vals( ((1, 2), ((3, 4), ())) ) 4 """ if : return 0 elif type(pair) is int: return else return Last modified: Thu Feb 20 20:10:46 2014 CS61A: Lecture #7 9

Example: Code def count_vals(pair): """Assuming PAIR is a numeric pair, the total number of integers contained in the pair. >>> count_vals(()) 0 >>> count_vals( (1, ()) ) 1 >>> count_vals( (1, 2) ) 2 >>> count_vals( ((1, 2), ((3, 4), ())) ) 4 """ if pair == (): return 0 elif type(pair) is int: return else return Last modified: Thu Feb 20 20:10:46 2014 CS61A: Lecture #7 9

Example: Code def count_vals(pair): """Assuming PAIR is a numeric pair, the total number of integers contained in the pair. >>> count_vals(()) 0 >>> count_vals( (1, ()) ) 1 >>> count_vals( (1, 2) ) 2 >>> count_vals( ((1, 2), ((3, 4), ())) ) 4 """ if pair == (): return 0 elif type(pair) is int: return 1 else return Last modified: Thu Feb 20 20:10:46 2014 CS61A: Lecture #7 9

Example: Code def count_vals(pair): """Assuming PAIR is a numeric pair, the total number of integers contained in the pair. >>> count_vals(()) 0 >>> count_vals( (1, ()) ) 1 >>> count_vals( (1, 2) ) 2 >>> count_vals( ((1, 2), ((3, 4), ())) ) 4 """ if pair == (): return 0 elif type(pair) is int: return 1 else return #ints in pair[0] + #ints in pair[1] Last modified: Thu Feb 20 20:10:46 2014 CS61A: Lecture #7 9

Example: Code def count_vals(pair): """Assuming PAIR is a numeric pair, the total number of integers contained in the pair. >>> count_vals(()) 0 >>> count_vals( (1, ()) ) 1 >>> count_vals( (1, 2) ) 2 >>> count_vals( ((1, 2), ((3, 4), ())) ) 4 """ if pair == (): return 0 elif type(pair) is int: return 1 else return count_vals(pair[0]) + count_vals(pair[1]) Last modified: Thu Feb 20 20:10:46 2014 CS61A: Lecture #7 9

The Recursive Leap of Faith Toimplementcount vals,wetrusteditscommenttobecorrect,even as we implemented it. This is the essence of recursive thinking. If we can show that Our implementation is correct given that the comment is correct, And if we can show that the process must terminate, then the comment (the specification of the function) is correct. For recursive data structures, showing termination involves using a form of Noetherian induction. Last modified: Thu Feb 20 20:10:46 2014 CS61A: Lecture #7 10

Noetherian Induction A relation on values is well-founded if there are no infinite descending chains: That is, if you start at some value and keep stepping to smaller values(according to the relation), then you must always get to a minimal value after finite steps. E.g., natural or positive numbers under <. Or numeric pairs under is an element of. Principle of Noetherian induction (named after Emmy Noether): (Source: http://en.wikipedia.org/wiki/emmy Noether) If P(x) is statement about values x from a well-founded set, and If P(x)istruewhenever P(y)istruefor all y < x, Then P(x) is true for all x. Last modified: Thu Feb 20 20:10:46 2014 CS61A: Lecture #7 11

Induction and Recursion Recursive programs are justified(and constructed) by inductive reasoning. Basic structure: def f(x): if There are no valid values x: # The base case return A value that s correct when x is minimal else: # Use The inductive hypothesis return A solution constructed using f(y) where y x The meaning of depends on the application. In place of return might also use side-effect-producing code. Last modified: Thu Feb 20 20:10:46 2014 CS61A: Lecture #7 12