61A Lecture 32. Wednesday, November 14

Size: px
Start display at page:

Download "61A Lecture 32. Wednesday, November 14"

Transcription

1 61A Lecture 32 Wednesday, November 14

2 Processing Sequential Data 2

3 Processing Sequential Data Many data sets can be viewed and processed sequentially: 2

4 Processing Sequential Data Many data sets can be viewed and processed sequentially: The set of all Twitter posts 2

5 Processing Sequential Data Many data sets can be viewed and processed sequentially: The set of all Twitter posts Votes cast in a presidential election 2

6 Processing Sequential Data Many data sets can be viewed and processed sequentially: The set of all Twitter posts Votes cast in a presidential election Sensor readings of an airplane 2

7 Processing Sequential Data Many data sets can be viewed and processed sequentially: The set of all Twitter posts Votes cast in a presidential election Sensor readings of an airplane The set of all positive integers 2

8 Processing Sequential Data Many data sets can be viewed and processed sequentially: The set of all Twitter posts Votes cast in a presidential election Sensor readings of an airplane The set of all positive integers However, the sequence interface we developed previously does not always apply. 2

9 Processing Sequential Data Many data sets can be viewed and processed sequentially: The set of all Twitter posts Votes cast in a presidential election Sensor readings of an airplane The set of all positive integers However, the sequence interface we developed previously does not always apply. A sequence has a finite, known length 2

10 Processing Sequential Data Many data sets can be viewed and processed sequentially: The set of all Twitter posts Votes cast in a presidential election Sensor readings of an airplane The set of all positive integers However, the sequence interface we developed previously does not always apply. A sequence has a finite, known length A sequence support element selection for any element 2

11 Processing Sequential Data Many data sets can be viewed and processed sequentially: The set of all Twitter posts Votes cast in a presidential election Sensor readings of an airplane The set of all positive integers However, the sequence interface we developed previously does not always apply. A sequence has a finite, known length A sequence support element selection for any element In most cases, satisfying the sequence interface requires storing the entire sequence in a computer's memory. 2

12 Processing Sequential Data Many data sets can be viewed and processed sequentially: The set of all Twitter posts Votes cast in a presidential election Sensor readings of an airplane The set of all positive integers However, the sequence interface we developed previously does not always apply. A sequence has a finite, known length A sequence support element selection for any element In most cases, satisfying the sequence interface requires storing the entire sequence in a computer's memory. Today: Efficient representations of sequential data 2

13 Implicit Sequences 3

14 Implicit Sequences An implicit sequence is a representation of sequential data that does not explicitly store each element. 3

15 Implicit Sequences An implicit sequence is a representation of sequential data that does not explicitly store each element. Example: The range class represents consecutive integers. 3

16 Implicit Sequences An implicit sequence is a representation of sequential data that does not explicitly store each element. Example: The range class represents consecutive integers. The range is represented by two values: start and end. 3

17 Implicit Sequences An implicit sequence is a representation of sequential data that does not explicitly store each element. Example: The range class represents consecutive integers. The range is represented by two values: start and end. The length and elements are computed on demand. 3

18 Implicit Sequences An implicit sequence is a representation of sequential data that does not explicitly store each element. Example: The range class represents consecutive integers. The range is represented by two values: start and end. The length and elements are computed on demand. Constant space for arbitrarily large sequences. 3

19 Implicit Sequences An implicit sequence is a representation of sequential data that does not explicitly store each element. Example: The range class represents consecutive integers. The range is represented by two values: start and end. The length and elements are computed on demand. Constant space for arbitrarily large sequences. Demo 3

20 The Iterator Interface 4

21 The Iterator Interface An iterator is an object that can provide the next element of a (possibly implicit) sequence. 4

22 The Iterator Interface An iterator is an object that can provide the next element of a (possibly implicit) sequence. The iterator interface has two methods: 4

23 The Iterator Interface An iterator is an object that can provide the next element of a (possibly implicit) sequence. The iterator interface has two methods: next (self) returns the next element in the sequence 4

24 The Iterator Interface An iterator is an object that can provide the next element of a (possibly implicit) sequence. The iterator interface has two methods: next (self) returns the next element in the sequence iter (self) returns an equivalent iterator (Why?) 4

25 The Iterator Interface An iterator is an object that can provide the next element of a (possibly implicit) sequence. The iterator interface has two methods: next (self) returns the next element in the sequence iter (self) returns an equivalent iterator (Why?) The next function invokes the next method on its argument. 4

26 The Iterator Interface An iterator is an object that can provide the next element of a (possibly implicit) sequence. The iterator interface has two methods: next (self) returns the next element in the sequence iter (self) returns an equivalent iterator (Why?) The next function invokes the next method on its argument. If there is no next element, then the next method of an iterator should raise a StopIteration exception. 4

27 The Iterator Interface An iterator is an object that can provide the next element of a (possibly implicit) sequence. The iterator interface has two methods: next (self) returns the next element in the sequence iter (self) returns an equivalent iterator (Why?) The next function invokes the next method on its argument. If there is no next element, then the next method of an iterator should raise a StopIteration exception. Demo 4

28 The For Statement 5

29 The For Statement for <name> in <expression>: <suite> 5

30 The For Statement for <name> in <expression>: <suite> 1. Evaluate the header <expression>, which yields an iterable object. 5

31 The For Statement for <name> in <expression>: <suite> 1. Evaluate the header <expression>, which yields an iterable object. 2. For each element in that sequence, in order: 5

32 The For Statement for <name> in <expression>: <suite> 1. Evaluate the header <expression>, which yields an iterable object. 2. For each element in that sequence, in order: A. Bind <name> to that element in the first frame of the current environment. 5

33 The For Statement for <name> in <expression>: <suite> 1. Evaluate the header <expression>, which yields an iterable object. 2. For each element in that sequence, in order: A. Bind <name> to that element in the first frame of the current environment. B. Execute the <suite>. 5

34 The For Statement for <name> in <expression>: <suite> 1. Evaluate the header <expression>, which yields an iterable object. 2. For each element in that sequence, in order: A. Bind <name> to that element in the first frame of the current environment. B. Execute the <suite>. An iterable object has a method iter that returns an iterator. 5

35 The For Statement for <name> in <expression>: <suite> 1. Evaluate the header <expression>, which yields an iterable object. 2. For each element in that sequence, in order: A. Bind <name> to that element in the first frame of the current environment. B. Execute the <suite>. An iterable object has a method iter that returns an iterator. >>> counts = [1, 2, 3] >>> for item in counts: print(item)

36 The For Statement for <name> in <expression>: <suite> 1. Evaluate the header <expression>, which yields an iterable object. 2. For each element in that sequence, in order: A. Bind <name> to that element in the first frame of the current environment. B. Execute the <suite>. An iterable object has a method iter that returns an iterator. >>> counts = [1, 2, 3] >>> for item in counts: print(item) >>> counts = [1, 2, 3] >>> items = counts. iter () >>> try: while True: item = items. next () print(item) except StopIteration: pass

37 Generators and Generator Functions 6

38 Generators and Generator Functions A generator is an iterator backed by a generator function. 6

39 Generators and Generator Functions A generator is an iterator backed by a generator function. A generator function is a function that yields values. 6

40 Generators and Generator Functions A generator is an iterator backed by a generator function. A generator function is a function that yields values. When a generator function is called, it returns a generator. 6

41 Generators and Generator Functions A generator is an iterator backed by a generator function. A generator function is a function that yields values. When a generator function is called, it returns a generator. >>> def letters_generator(): current = 'a' while current <= 'd': yield current current = chr(ord(current)+1) 6

42 Generators and Generator Functions A generator is an iterator backed by a generator function. A generator function is a function that yields values. When a generator function is called, it returns a generator. >>> def letters_generator(): current = 'a' while current <= 'd': yield current current = chr(ord(current)+1) >>> for letter in letters_generator(): print(letter) 6

43 Generators and Generator Functions A generator is an iterator backed by a generator function. A generator function is a function that yields values. When a generator function is called, it returns a generator. >>> def letters_generator(): current = 'a' while current <= 'd': yield current current = chr(ord(current)+1) >>> for letter in letters_generator(): print(letter) a b c d 6

44 Streams 7

45 Streams A stream is a recursive list with an explicit first element and an implicit rest of the list. 7

46 Streams A stream is a recursive list with an explicit first element and an implicit rest of the list. class Stream(object): """A lazily computed recursive list.""" 7

47 Streams A stream is a recursive list with an explicit first element and an implicit rest of the list. class Stream(object): """A lazily computed recursive list.""" class empty(object): def repr (self): return 'Stream.empty' empty = empty() 7

48 Streams A stream is a recursive list with an explicit first element and an implicit rest of the list. class Stream(object): """A lazily computed recursive list.""" class empty(object): def repr (self): return 'Stream.empty' empty = empty() def init (self, first, compute_rest=lambda: empty): assert callable(compute_rest), 'compute_rest must be callable.' self.first = first self._compute_rest = compute_rest self._rest = None 7

49 Streams A stream is a recursive list with an explicit first element and an implicit rest of the list. class Stream(object): """A lazily computed recursive list.""" class empty(object): def repr (self): return 'Stream.empty' empty = empty() def init (self, first, compute_rest=lambda: empty): assert callable(compute_rest), 'compute_rest must be callable.' self.first = first self._compute_rest = compute_rest self._rest = def rest(self): """Return the rest of the stream, computing it if necessary.""" if self._compute_rest is not None: self._rest = self._compute_rest() self._compute_rest = None return self._rest 7

50 Integer Streams 8

51 Integer Streams An integer stream is a stream of consecutive integers. An integer stream starting at k consists of k and a function that returns the integer stream starting at k+1. 8

52 Integer Streams An integer stream is a stream of consecutive integers. An integer stream starting at k consists of k and a function that returns the integer stream starting at k+1. def make_integer_stream(first=1): """Return a stream of consecutive integers, starting with first. >>> s = make_integer_stream(3) >>> s.first 3 >>> s.rest.first 4 """" def compute_rest(): return make_integer_stream(first+1) return Stream(first, compute_rest) 8

53 Mapping a Function over a Stream 9

54 Mapping a Function over a Stream Mapping a function over a stream applies a function only to the first element at first, but computes the rest lazily. 9

55 Mapping a Function over a Stream Mapping a function over a stream applies a function only to the first element at first, but computes the rest lazily. def map_stream(fn, s): """Map a function fn over the elements of a stream s.""" if s is Stream.empty: return s def compute_rest(): return map_stream(fn, s.rest) return Stream(fn(s.first), compute_rest) 9

56 Mapping a Function over a Stream Mapping a function over a stream applies a function only to the first element at first, but computes the rest lazily. def map_stream(fn, s): """Map a function fn over the elements of a stream s.""" if s is Stream.empty: return s def compute_rest(): return map_stream(fn, s.rest) return Stream(fn(s.first), compute_rest) Demo 9

57 Filtering a Stream 10

58 Filtering a Stream When filtering a stream, processing continues until an element is kept in the output. 10

59 Filtering a Stream When filtering a stream, processing continues until an element is kept in the output. def filter_stream(fn, s): """Filter stream s with predicate function fn.""" if s is Stream.empty: return s def compute_rest(): return filter_stream(fn, s.rest) if fn(s.first): return Stream(s.first, compute_rest) else: return compute_rest() 10

60 A Stream of Primes 11

61 A Stream of Primes The stream of integers not divisible by any k <= n is: 11

62 A Stream of Primes The stream of integers not divisible by any k <= n is: The stream of integers not divisible by any k < n, 11

63 A Stream of Primes The stream of integers not divisible by any k <= n is: The stream of integers not divisible by any k < n, Filtered to remove any element divisible by n. 11

64 A Stream of Primes The stream of integers not divisible by any k <= n is: The stream of integers not divisible by any k < n, Filtered to remove any element divisible by n. Called the Sieve of Eratosthenes. 11

65 A Stream of Primes The stream of integers not divisible by any k <= n is: The stream of integers not divisible by any k < n, Filtered to remove any element divisible by n. Called the Sieve of Eratosthenes. 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 11

66 A Stream of Primes The stream of integers not divisible by any k <= n is: The stream of integers not divisible by any k < n, Filtered to remove any element divisible by n. Called the Sieve of Eratosthenes. 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 11

67 A Stream of Primes The stream of integers not divisible by any k <= n is: The stream of integers not divisible by any k < n, Filtered to remove any element divisible by n. Called the Sieve of Eratosthenes. 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 11

68 A Stream of Primes The stream of integers not divisible by any k <= n is: The stream of integers not divisible by any k < n, Filtered to remove any element divisible by n. Called the Sieve of Eratosthenes. 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 11

69 A Stream of Primes The stream of integers not divisible by any k <= n is: The stream of integers not divisible by any k < n, Filtered to remove any element divisible by n. Called the Sieve of Eratosthenes. 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 11

70 A Stream of Primes The stream of integers not divisible by any k <= n is: The stream of integers not divisible by any k < n, Filtered to remove any element divisible by n. Called the Sieve of Eratosthenes. 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 11

71 A Stream of Primes The stream of integers not divisible by any k <= n is: The stream of integers not divisible by any k < n, Filtered to remove any element divisible by n. Called the Sieve of Eratosthenes. 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 Demo 11

Lecture 27: Streams and Lazy Evaluation

Lecture 27: Streams and Lazy Evaluation Lecture 27: Streams and Lazy Evaluation Some of the most interesting real-world problems in computer science center around sequential data. DNA sequences. Web and cell-phone traffic streams. The social

More information

STREAMS, ITERATORS, AND BINARY TREES 10

STREAMS, ITERATORS, AND BINARY TREES 10 STREAMS, ITERATORS, AND BINARY TREES 10 COMPUTER SCIENCE 61A April 10, 2017 1 Streams A stream is a lazily-evaluated linked list. A stream s elements (except for the first element) are only computed when

More information

COMPUTER SCIENCE IN THE NEWS. CS61A Lecture 24 Infinite Sequences LAZY EVALUATION AGENDA 8/7/2012. Jom Magrotker UC Berkeley EECS July 30, 2012

COMPUTER SCIENCE IN THE NEWS. CS61A Lecture 24 Infinite Sequences LAZY EVALUATION AGENDA 8/7/2012. Jom Magrotker UC Berkeley EECS July 30, 2012 COMPUTER SCIENCE IN THE NEWS CS6A Lecture 24 Infinite Sequences Jom Magrotker UC Berkeley EECS July 30, 202 http://www.wired.com/threatlevel/202/07/reverse engineering iris scans/all/ 2 AGENDA Weeks to

More information

CS61A Lecture 24 Infinite Sequences. Jom Magrotker UC Berkeley EECS July 30, 2012

CS61A Lecture 24 Infinite Sequences. Jom Magrotker UC Berkeley EECS July 30, 2012 CS61A Lecture 24 Infinite Sequences Jom Magrotker UC Berkeley EECS July 30, 2012 COMPUTER SCIENCE IN THE NEWS http://www.wired.com/threatlevel/2012/07/reverse engineering iris scans/all/ 2 AGENDA Weeks

More information

STREAMS AND REVIEW 12

STREAMS AND REVIEW 12 STREAMS AND REVIEW 12 COMPUTER SCIENCE 61A April 23, 2014 1 Streams A stream is our third example of a lazy sequence. A stream is like a lazily evaluated Rlist. In other words, the stream s elements (except

More information

61A LECTURE 25 DECLARATIVE PROGRAMMING

61A LECTURE 25 DECLARATIVE PROGRAMMING 61A LCTUR 25 DCLARATIV PROGRAMMING Midterm grades up Class did well as a whole! glookup s test2 Regrades: Talk to your TA in person. Steven Tang and ric Tzeng August 6, 2013 Announcements Proj4 has been

More information

CS61A Lecture 36. Soumya Basu UC Berkeley April 15, 2013

CS61A Lecture 36. Soumya Basu UC Berkeley April 15, 2013 CS61A Lecture 36 Soumya Basu UC Berkeley April 15, 2013 Announcements HW11 due Wednesday Scheme project, contest out Our Sequence Abstraction Recall our previous sequence interface: A sequence has a finite,

More information

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

Structure and Interpretation of Computer Programs Spring 2014 Final (with corrections) CS 61A Structure and Interpretation of Computer Programs Spring 2014 Final (with corrections) INSTRUCTIONS You have 3 hours to complete the exam. The exam is open book and open notes. You may not use a

More information

ITERATORS AND STREAMS 9

ITERATORS AND STREAMS 9 ITERATORS AND STREAMS 9 COMPUTER SCIENCE 61A November 12, 2015 1 Iterators An iterator is an object that tracks the position in a sequence of values. It can return an element at a time, and it is only

More information

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

61A LECTURE 22 TAIL CALLS, ITERATORS. Steven Tang and Eric Tzeng July 30, 2013 61A LECTURE 22 TAIL CALLS, ITERATORS Steven Tang and Eric Tzeng July 30, 2013 Announcements Homework 12 due Thursday, not Monday. Take the time to get started on the project instead! Almost done with Scheme

More information

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs CS 6A Spring 0 Structure and Interpretation of Computer Programs Final INSTRUCTIONS You have hours to complete the exam. The exam is closed book, closed notes, closed computer, closed calculator, except

More information

ITERATORS AND GENERATORS 10

ITERATORS AND GENERATORS 10 ITERATORS AND GENERATORS COMPUTER SCIENCE 6A July 23, 25 Iterators An iterator is an object that tracks the position in a sequence of values. It can return an element at a time, and it is only good for

More information

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs CS 6A Summer 07 Structure and Interpretation of Computer Programs Final You have hours and 50 minutes to complete this exam. This exam is closed book, closed notes, closed computer, closed calculator,

More information

MEMOIZATION, RECURSIVE DATA, AND SETS

MEMOIZATION, RECURSIVE DATA, AND SETS MEMOIZATION, RECURSIVE DATA, AND SETS 4b COMPUTER SCIENCE 61A July 18, 2013 1 Memoization Later in this class, you ll learn about orders of growth and how to analyze exactly how efficient (or inefficient)

More information

Iterators & Generators

Iterators & Generators Iterators & Generators Sequences A sequence is something that you can: Index into Get the length of What are some examples of sequences? Sequences We ve been working with sequences all semester! Examples:

More information

61A LECTURE 15 MEMOIZATION, RECURSIVE DATA, SETS

61A LECTURE 15 MEMOIZATION, RECURSIVE DATA, SETS 61A LECTURE 15 MEMOIZATION, RECURSIVE DATA, SETS Steven Tang and Eric Tzeng July 18, 2013 Now in a wider screen format! Who am I? What am I doing here? First two weeks of class (Chapter 1): FUNCTIONS Computational

More information

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs CS 61A Summer 2013 Structure and Interpretation of Computer Programs Final Solutions INSTRUCTIONS ˆ You have 3 hours to complete the exam. ˆ The exam is closed book, closed notes, closed computer, closed

More information

COMPSCI 230 Discrete Math Prime Numbers January 24, / 15

COMPSCI 230 Discrete Math Prime Numbers January 24, / 15 COMPSCI 230 Discrete Math January 24, 2017 COMPSCI 230 Discrete Math Prime Numbers January 24, 2017 1 / 15 Outline 1 Prime Numbers The Sieve of Eratosthenes Python Implementations GCD and Co-Primes COMPSCI

More information

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs CS 61A Fall 2013 Structure and Interpretation of Computer Programs Final Solutions INSTRUCTIONS You have 3 hours to complete the exam. The exam is closed book, closed notes, closed computer, closed calculator,

More information

Delayed Expressions Fall 2017 Discussion 9: November 8, Iterables and Iterators. For Loops. Other Iterable Uses

Delayed Expressions Fall 2017 Discussion 9: November 8, Iterables and Iterators. For Loops. Other Iterable Uses CS 6A Delayed Expressions Fall 07 Discussion 9: November 8, 07 Iterables and Iterators An iterable is any container that can be processed sequentially. Examples include lists, tuples, strings, and dictionaries.

More information

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

INTERPRETERS 8. 1 Calculator COMPUTER SCIENCE 61A. November 3, 2016 INTERPRETERS 8 COMPUTER SCIENCE 61A November 3, 2016 1 Calculator We are beginning to dive into the realm of interpreting computer programs that is, writing programs that understand other programs. In

More information

LINKED LISTS AND MIDTERM REVIEW

LINKED LISTS AND MIDTERM REVIEW LINKED LISTS AND MIDTERM REVIEW COMPUTER SCIENCE MENTORS 61A March 12 to March 14, 2018 For each of the following problems, assume linked lists are defined as follows: class Link: empty = () def init (self,

More information

CS450 - Structure of Higher Level Languages

CS450 - Structure of Higher Level Languages Spring 2018 Streams February 24, 2018 Introduction Streams are abstract sequences. They are potentially infinite we will see that their most interesting and powerful uses come in handling infinite sequences.

More information

Lecture #23: Conversion and Type Inference

Lecture #23: Conversion and Type Inference Lecture #23: Conversion and Type Inference Administrivia. Due date for Project #2 moved to midnight tonight. Midterm mean 20, median 21 (my expectation: 17.5). Last modified: Fri Oct 20 10:46:40 2006 CS164:

More information

LINKED LISTS AND MIDTERM REVIEW 6

LINKED LISTS AND MIDTERM REVIEW 6 LINKED LISTS AND MIDTERM REVIEW 6 COMPUTER SCIENCE 61A October 13, 2016 1 Linked Lists 1.1 Implementation class Link: empty = () def init (self, first, rest=empty): assert rest is Link.empty or isinstance(rest,

More information

Fall 2018 Lecture N

Fall 2018 Lecture N 15-150 Fall 2018 Lecture N Tuesday, 20 November I m too lazy to figure out the correct number Stephen Brookes midterm2 Mean: 79.5 Std Dev: 18.4 Median: 84 today or, we could procrastinate lazy functional

More information

TAIL CALLS, ITERATORS, AND GENERATORS 11

TAIL CALLS, ITERATORS, AND GENERATORS 11 TAIL CALLS, ITERATORS, AND GENERATORS 11 COMPUTER SCIENCE 61A November 13, 214 1 Tail Calls Scheme implements tail-call optimization, which allows programmers to write recursive functions that use a constant

More information

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

Conversion vs. Subtyping. Lecture #23: Conversion and Type Inference. Integer Conversions. Conversions: Implicit vs. Explicit. Object x = Hello; Lecture #23: Conversion and Type Inference Administrivia. Due date for Project #2 moved to midnight tonight. Midterm mean 20, median 21 (my expectation: 17.5). In Java, this is legal: Object x = "Hello";

More information

Lecture 16: Recapitulations. Lecture 16: Recapitulations p. 1

Lecture 16: Recapitulations. Lecture 16: Recapitulations p. 1 Lecture 16: Recapitulations Lecture 16: Recapitulations p. 1 Parallel computing and programming in general Parallel computing a form of parallel processing by utilizing multiple computing units concurrently

More information

Working with Lists 4

Working with Lists 4 CS 61A Lecture 10 Announcements Lists ['Demo'] Working with Lists 4 Working with Lists >>> digits = [1, 8, 2, 8] 4 Working with Lists >>> digits = [1, 8, 2, 8] >>> digits = [2//2, 2+2+2+2, 2, 2*2*2] 4

More information

Important note: In all cases code should be clearly-written and should include a brief explanation in English explaining the design of your code.

Important note: In all cases code should be clearly-written and should include a brief explanation in English explaining the design of your code. Coursework PY1 (Questions on Python) Deadline: 17 November 2017 Important note: In all cases code should be clearly-written and should include a brief explanation in English explaining the design of your

More information

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines. Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

Final Exam Solutions. Structure and Interpretation of Computer Programs. Fall 2011 /12 /16 /12 /18 /10 /12 /80 INSTRUCTIONS

Final Exam Solutions. Structure and Interpretation of Computer Programs. Fall 2011 /12 /16 /12 /18 /10 /12 /80 INSTRUCTIONS CS 61A Fall 2011 Structure and Interpretation of Computer Programs Final Exam Solutions INSTRUCTIONS You have 3 hours to complete the exam. The exam is closed book, closed notes, closed computer, closed

More information

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

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

CS61A Lecture 15. Amir Kamil UC Berkeley February 25, 2013 CS61A Lecture 15 Amir Kamil UC Berkeley February 25, 2013 Announcements HW5 due on Wednesday Trends project out Partners are required; find one in lab or on Piazza Will not work in IDLE New bug submission

More information

F21SC Industrial Programming: Functional Programming in Python

F21SC Industrial Programming: Functional Programming in Python F21SC Industrial Programming: Functional Programming in Python Hans-Wolfgang Loidl School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh Semester 1 2017/18 0 No proprietary software

More information

RLISTS AND THE ENVIRONMENT MODEL 9

RLISTS AND THE ENVIRONMENT MODEL 9 RLISTS AND THE ENVIRONMENT MODEL 9 COMPUTER SCIENCE 61A July 17, 2012 1 Recursive Lists (RLists) Earlier in the course, we worked with the Immutable Recursive List (IRList), which is an abstract data type

More information

G Programming Languages - Fall 2012

G Programming Languages - Fall 2012 G22.2110-003 Programming Languages - Fall 2012 Lecture 3 Thomas Wies New York University Review Last week Names and Bindings Lifetimes and Allocation Garbage Collection Scope Outline Control Flow Sequencing

More information

return total def cube(k): return pow(k, 3) >>> summation(5, cube) 225 """ total, k = 0, 1 while k <= n:

return total def cube(k): return pow(k, 3) >>> summation(5, cube) 225  total, k = 0, 1 while k <= n: CS 6A Midterm Study Guide Page Import statement mul(add(, mul(, 6)), add(, 5)) Pure Functions - abs(number): Assignment statement Name Binding Value mul 6 add(, mul(, 6)) add(, 5), (x, y): Code (left):

More information

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs CS 61A Fall 016 Structure and Interpretation of Computer Programs Midterm Solutions INSTRUCTIONS You have hours to complete the exam. The exam is closed book, closed notes, closed computer, closed calculator,

More information

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs CS 6A Summer 5 Structure and Interpretation of Computer Programs Midterm Solutions INSTRUCTIONS You have hours to complete the exam. The exam is closed book, closed notes, closed computer, closed calculator,

More information

Algorithmic Thinking: Computing with Lists

Algorithmic Thinking: Computing with Lists Algorithmic Thinking: Computing with Lists So Far in Python Data types: int, float, Boolean, string Assignments, function definitions Control structures: For loops, while loops, conditionals Last Lecture

More information

INTERPRETERS AND TAIL CALLS 9

INTERPRETERS AND TAIL CALLS 9 INTERPRETERS AND TAIL CALLS 9 COMPUTER SCIENCE 61A April 9, 2015 We are beginning to dive into the realm of interpreting computer programs that is, writing programs that understand other programs. In order

More information

Table 1 below illustrates the construction for the case of 11 integers selected from 20.

Table 1 below illustrates the construction for the case of 11 integers selected from 20. Q: a) From the first 200 natural numbers 101 of them are arbitrarily chosen. Prove that among the numbers chosen there exists a pair such that one divides the other. b) Prove that if 100 numbers are chosen

More information

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs CS 61A Spring 2017 Structure and Interpretation of Computer Programs Test 2 (revised) INSTRUCTIONS You have 2 hours to complete the exam. The exam is open book, open notes, closed computer, closed calculator.

More information

Object-Oriented Design Lecture 13 CSU 370 Fall 2008 (Pucella) Friday, Oct 31, 2008

Object-Oriented Design Lecture 13 CSU 370 Fall 2008 (Pucella) Friday, Oct 31, 2008 Object-Oriented Design Lecture 13 CSU 370 Fall 2008 (Pucella) Friday, Oct 31, 2008 Laziness For this lecture, I want to return to something that came up during the last homework, the third homework where

More information

Lecture Notes on Program Equivalence

Lecture Notes on Program Equivalence Lecture Notes on Program Equivalence 15-312: Foundations of Programming Languages Frank Pfenning Lecture 24 November 30, 2004 When are two programs equal? Without much reflection one might say that two

More information

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs CS 61A Fall 2018 Structure and Interpretation of Computer Programs Final INSTRUCTIONS You have 3 hours to complete the exam. The exam is closed book, closed notes, closed computer, closed calculator, except

More information

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs CS 61A Spring 2015 Structure and Interpretation of Computer Programs Final Exam INSTRUCTIONS You have 3 hours to complete the exam. The exam is closed book, closed notes, closed computer, closed calculator,

More information

1 Truth. 2 Conditional Statements. Expressions That Can Evaluate to Boolean Values. Williams College Lecture 4 Brent Heeringa, Bill Jannen

1 Truth. 2 Conditional Statements. Expressions That Can Evaluate to Boolean Values. Williams College Lecture 4 Brent Heeringa, Bill Jannen 1 Truth Last lecture we learned about the int, float, and string types. Another very important object type in Python is the boolean type. The two reserved keywords True and False are values with type boolean.

More information

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs CS 61A Fall 2018 Structure and Interpretation of Computer Programs Final Solutions INSTRUCTIONS You have 3 hours to complete the exam. The exam is closed book, closed notes, closed computer, closed calculator,

More information

Sometimes it s good to be lazy

Sometimes it s good to be lazy Chapter 8 Sometimes it s good to be lazy Typically, languages such as OCaml (SML, Lisp or Scheme) evaluate expressions by a call-by-value discipline. All variables in OCaml are bound by value, which means

More information

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs CS 61A Spring 2017 Structure and Interpretation of Computer Programs Test 2 (revised) Solutions INSTRUCTIONS You have 2 hours to complete the exam. The exam is open book, open notes, closed computer, closed

More information

CSI33 Data Structures

CSI33 Data Structures Outline Department of Mathematics and Computer Science Bronx Community College September 25, 2017 Outline Outline 1 Chapter 4: Linked Structures and Chapter 4: Linked Structures and Outline 1 Chapter 4:

More information

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

Lecture #15: Generic Functions and Expressivity. Last modified: Wed Mar 1 15:51: CS61A: Lecture #16 1 Lecture #15: Generic Functions and Expressivity Last modified: Wed Mar 1 15:51:48 2017 CS61A: Lecture #16 1 Consider the function find: Generic Programming def find(l, x, k): """Return the index in L of

More information

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

Lecture #13: Type Inference and Unification. Typing In the Language ML. Type Inference. Doing Type Inference Lecture #13: Type Inference and Unification Typing In the Language ML Examples from the language ML: fun map f [] = [] map f (a :: y) = (f a) :: (map f y) fun reduce f init [] = init reduce f init (a ::

More information

61A Lecture 6. Monday, February 2

61A Lecture 6. Monday, February 2 61A Lecture 6 Monday, February 2 Announcements Homework 2 due Monday 2/2 @ 11:59pm Project 1 due Thursday 2/5 @ 11:59pm Project party on Tuesday 2/3 5pm-6:30pm in 2050 VLSB Partner party on Wednesday 2/4

More information

15110 Principles of Compu5ng, Carnegie Mellon University - CORTINA. Finding the maximum. Required: a non-empty list of integers.

15110 Principles of Compu5ng, Carnegie Mellon University - CORTINA. Finding the maximum. Required: a non-empty list of integers. UNIT 3C Using Loops and Condi5onals 1 Finding the maximum Required: a non-empty list of integers. 1. Set max equal to the first number in the list. 2. For each number n in the list: a. If n is greater

More information

Structure and Interpretation of Computer Programs Summer 2015 Midterm 2

Structure and Interpretation of Computer Programs Summer 2015 Midterm 2 CS 6A Structure and Interpretation of Computer Programs Summer 05 Midterm INSTRUCTIONS You have hours to complete the exam. The exam is closed book, closed notes, closed computer, closed calculator, except

More information

UCT Algorithm Circle: Number Theory

UCT Algorithm Circle: Number Theory UCT Algorithm Circle: 7 April 2011 Outline Primes and Prime Factorisation 1 Primes and Prime Factorisation 2 3 4 Some revision (hopefully) What is a prime number? An integer greater than 1 whose only factors

More information

FRAC: Language Reference Manual

FRAC: Language Reference Manual FRAC: Language Reference Manual Justin Chiang jc4127 Kunal Kamath kak2211 Calvin Li ctl2124 Anne Zhang az2350 1. Introduction FRAC is a domain-specific programming language that enables the programmer

More information

Outline. LList: A Linked Implementation of a List ADT Iterators Links vs. Arrays In-class work. 1 Chapter 4: Linked Structures and Iterators

Outline. LList: A Linked Implementation of a List ADT Iterators Links vs. Arrays In-class work. 1 Chapter 4: Linked Structures and Iterators Chapter 4: Linked Structures and Outline 1 Chapter 4: Linked Structures and Chapter 4: Linked Structures and Using the ListNode Class Ideas about Linked List Implementation We have a pretty good feeling

More information

Streams and Evalutation Strategies

Streams and Evalutation Strategies Data and Program Structure Streams and Evalutation Strategies Lecture V Ahmed Rezine Linköpings Universitet TDDA69, VT 2014 Lecture 2: Class descriptions - message passing ( define ( make-account balance

More information

Scheme Quick Reference

Scheme Quick Reference Scheme Quick Reference COSC 18 Fall 2003 This document is a quick reference guide to common features of the Scheme language. It is not intended to be a complete language reference, but it gives terse summaries

More information

6.001 Notes: Section 17.5

6.001 Notes: Section 17.5 6.001 Notes: Section 17.5 Slide 17.5.1 Now, let's look at one example in which changing the evaluation model allows us to explore a very different kind of computational problem. Our goal is to show how

More information

CITS3211 FUNCTIONAL PROGRAMMING. 7. Lazy evaluation and infinite lists

CITS3211 FUNCTIONAL PROGRAMMING. 7. Lazy evaluation and infinite lists CITS3211 FUNCTIONAL PROGRAMMING 7. Lazy evaluation and infinite lists Summary: This lecture introduces lazy evaluation and infinite lists in functional languages. cs123 notes: Lecture 19 R.L. While, 1997

More information

61A Lecture 19. Wednesday, October 12

61A Lecture 19. Wednesday, October 12 61A Lecture 19 Wednesday, October 12 What Are Programs? Once upon a time, people wrote programs on blackboards Every once in a while, they would "punch in" a program Now, we type programs as text files

More information

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

CS61A Lecture 9 Immutable Data Structures. Jom Magrotker UC Berkeley EECS July 2, 2012 CS61A Lecture 9 Immutable Data Structures Jom Magrotker UC Berkeley EECS July 2, 2012 COMPUTER SCIENCE IN THE NEWS Google unveils Glass at Google I/O, June 27 Prototypes available to developers at the

More information

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

Interpreters and Tail Calls Fall 2017 Discussion 8: November 1, 2017 Solutions. 1 Calculator. calc> (+ 2 2) 4 CS 61A Interpreters and Tail Calls Fall 2017 Discussion 8: November 1, 2017 Solutions 1 Calculator We are beginning to dive into the realm of interpreting computer programs that is, writing programs that

More information

Beyond Blocks: Python Session #1

Beyond Blocks: Python Session #1 Beyond Blocks: Session #1 CS10 Spring 2013 Thursday, April 30, 2013 Michael Ball Beyond Blocks : : Session #1 by Michael Ball adapted from Glenn Sugden is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike

More information

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

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)) SCHEME 0 COMPUTER SCIENCE 6A July 26, 206 0. Warm Up: Conditional Expressions. What does Scheme print? scm> (if (or #t (/ 0 (/ 0 scm> (if (> 4 3 (+ 2 3 4 (+ 3 4 (* 3 2 scm> ((if (< 4 3 + - 4 00 scm> (if

More information

Computer Programming

Computer Programming Computer Programming Dr. Deepak B Phatak Dr. Supratik Chakraborty Department of Computer Science and Engineering Session: Recap of Arrays and Simultaneous Equations (S31 S35) Dr. Deepak B. Phatak & Dr.

More information

Declarative Concurrency (CTM 4)

Declarative Concurrency (CTM 4) Declarative Concurrency (CTM 4) Carlos Varela Rensselaer Polytechnic Institute Adapted with permission from: Seif Haridi KTH Peter Van Roy UCL November 21, 2014 C. Varela; Adapted with permission from

More information

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs CS 61A Fall 2018 Structure and Interpretation of Computer Programs Midterm 2 Solutions INSTRUCTIONS You have 2 hours to complete the exam. The exam is closed book, closed notes, closed computer, closed

More information

61A Lecture 7. Monday, September 16

61A Lecture 7. Monday, September 16 61A Lecture 7 Monday, September 16 Announcements Homework 2 due Tuesday at 11:59pm Project 1 due Thursday at 11:59pm Extra debugging office hours in Soda 405: Tuesday 6-8, Wednesday 6-7, Thursday 5-7 Readers

More information

Index. Cambridge University Press Functional Programming Using F# Michael R. Hansen and Hans Rischel. Index.

Index. Cambridge University Press Functional Programming Using F# Michael R. Hansen and Hans Rischel. Index. (),23 (*,3 ->,3,32 *,11 *),3.[...], 27, 186 //,3 ///,3 ::, 71, 80 :=, 182 ;, 179 ;;,1 @, 79, 80 @"...",26 >,38,35

More information

61A Lecture 7. Monday, September 15

61A Lecture 7. Monday, September 15 61A Lecture 7 Monday, September 15 Announcements Homework 2 due Monday 9/15 at 11:59pm Project 1 deadline extended, due Thursday 9/18 at 11:59pm! Extra credit point if you submit by Wednesday 9/17 at 11:59pm

More information

Python iterators and generators

Python iterators and generators Iterators and generators Python iterators and generators Python makes good use of iterators And has a special kind of generator func7on that is powerful and useful We ll look at what both are And why they

More information

CS 61A Orders of Growth & Linked Lists Spring 2018 Discussion 6: March 7, Warmup

CS 61A Orders of Growth & Linked Lists Spring 2018 Discussion 6: March 7, Warmup CS 61A Orders of Growth & Linked Lists Spring 2018 Discussion 6: March 7, 2018 1 Warmup What is the order of growth for the following functions? (for example, Θ(n)) Answer in terms of Θ 11 def fib_iter(n):

More information

Lecture 27. Lecture 27: Regular Expressions and Python Identifiers

Lecture 27. Lecture 27: Regular Expressions and Python Identifiers Lecture 27 Lecture 27: Regular Expressions and Python Identifiers Python Syntax Python syntax makes very few restrictions on the ways that we can name our variables, functions, and classes. Variables names

More information

Putting the fun in functional programming

Putting the fun in functional programming CM20167 Topic 4: Map, Lambda, Filter Guy McCusker 1W2.1 Outline 1 Introduction to higher-order functions 2 Map 3 Lambda 4 Filter Guy McCusker (1W2.1 CM20167 Topic 4 2 / 42 Putting the fun in functional

More information

Scheme Quick Reference

Scheme Quick Reference Scheme Quick Reference COSC 18 Winter 2003 February 10, 2003 1 Introduction This document is a quick reference guide to common features of the Scheme language. It is by no means intended to be a complete

More information

Sorted list. Find 104. How many comparisons with sequential search? A. 1 B. 4 C. 11 D. 12 E. 16. Vote at m.socrative.com. Room number

Sorted list. Find 104. How many comparisons with sequential search? A. 1 B. 4 C. 11 D. 12 E. 16. Vote at m.socrative.com. Room number Sorted list 7 8 15 53 54 61 66 75 77 99 104 111 123 124 150 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Find 104. How many comparisons with sequential search? A. 1 B. 4 C. 11 D. 12 E. 16 Vote at m.socrative.com.

More information

Name :. Roll No. :... Invigilator s Signature : INTRODUCTION TO PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70

Name :. Roll No. :... Invigilator s Signature : INTRODUCTION TO PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 Name :. Roll No. :..... Invigilator s Signature :.. 2011 INTRODUCTION TO PROGRAMMING Time Allotted : 3 Hours Full Marks : 70 The figures in the margin indicate full marks. Candidates are required to give

More information

Streams. CS21b: Structure and Interpretation of Computer Programs Spring Term, 2004

Streams. CS21b: Structure and Interpretation of Computer Programs Spring Term, 2004 Streams CS21b: Structure and Interpretation of Computer Programs Spring Term, 2004 We ve already seen how evaluation order can change behavior when we program with state. Now we want to investigate how

More information

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

Fall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives CS 6A Scheme Fall 208 Discussion 8: October 24, 208 Solutions Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write

More information

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

CSC 148 Lecture 3. Dynamic Typing, Scoping, and Namespaces. Recursion CSC 148 Lecture 3 Dynamic Typing, Scoping, and Namespaces Recursion Announcements Python Ramp Up Session Monday June 1st, 1 5pm. BA3195 This will be a more detailed introduction to the Python language

More information

Call-by-name evaluation

Call-by-name evaluation Lecture IX Keywords: call-by-value, call-by-name, and call-by-need evaluation; lazy datatypes: sequences, streams, trees; lazy evaluation; sieve of Eratosthenes; breadth-first and depth-first traversals.

More information

Advanced topics, part 2

Advanced topics, part 2 CS 1 Introduction to Computer Programming Lecture 24: December 5, 2012 Advanced topics, part 2 Last time Advanced topics, lecture 1 recursion first-class functions lambda expressions higher-order functions

More information

Python: Functions and Generators. Giuseppe Attardi

Python: Functions and Generators. Giuseppe Attardi Python: Functions and Generators Giuseppe Attardi Functional Programming Slides by Felix Hernandez-Campos List Comprehensions >>> freshfruit = [' banana', ' loganberry ', 'passion fruit '] >>> [x.strip()

More information

Last week. Last week: We learned how to do simple procedural programming Python. This week: ow of control. for i in range(0,10): print i

Last week. Last week: We learned how to do simple procedural programming Python. This week: ow of control. for i in range(0,10): print i Last week Last week: We learned how to do simple procedural programming Python. for i in range(0,10): print i def fibonacci( n ): a = 1 b = 1 for i in range(1,n): a,b=b,a+b return a This week: ow of control.

More information

61A Lecture 2. Wednesday, September 4, 2013

61A Lecture 2. Wednesday, September 4, 2013 61A Lecture 2 Wednesday, September 4, 2013 Names, Assignment, and User-Defined Functions (Demo) Types of Expressions Primitive expressions: 2 add 'hello' Number or Numeral Name String Call expressions:

More information

Programming in MATLAB

Programming in MATLAB 8. Program Flow and Recursion Faculty of mathematics, physics and informatics Comenius University in Bratislava November 25th, 2015 Program Flow Program Flow in the first lecture: one command at a time

More information

Lecture 1 Contracts. 1 A Mysterious Program : Principles of Imperative Computation (Spring 2018) Frank Pfenning

Lecture 1 Contracts. 1 A Mysterious Program : Principles of Imperative Computation (Spring 2018) Frank Pfenning Lecture 1 Contracts 15-122: Principles of Imperative Computation (Spring 2018) Frank Pfenning In these notes we review contracts, which we use to collectively denote function contracts, loop invariants,

More information

Lecture Notes, CSE 232, Fall 2014 Semester

Lecture Notes, CSE 232, Fall 2014 Semester Lecture Notes, CSE 232, Fall 2014 Semester Dr. Brett Olsen Week 11 - Number Theory Number theory is the study of the integers. The most basic concept in number theory is divisibility. We say that b divides

More information

CSI33 Data Structures

CSI33 Data Structures Outline Department of Mathematics and Computer Science Bronx Community College October 24, 2016 Outline Outline 1 Chapter 7: Trees Outline Chapter 7: Trees 1 Chapter 7: Trees The Binary Search Property

More information

CS 1110: Introduction to Computing Using Python Loop Invariants

CS 1110: Introduction to Computing Using Python Loop Invariants CS 1110: Introduction to Computing Using Python Lecture 21 Loop Invariants [Andersen, Gries, Lee, Marschner, Van Loan, White] Announcements Prelim 2 conflicts due by midnight tonight Lab 11 is out Due

More information

Inductive Data Types

Inductive Data Types Inductive Data Types Lars-Henrik Eriksson Functional Programming 1 Original slides by Tjark Weber Lars-Henrik Eriksson (UU) Inductive Data Types 1 / 42 Inductive Data Types Today Today New names for old

More information

CS1 Lecture 5 Jan. 26, 2018

CS1 Lecture 5 Jan. 26, 2018 CS1 Lecture 5 Jan. 26, 2018 HW1 due Monday, 9:00am. Notes: Do not write all the code at once (for Q1 and 2) before starting to test. Take tiny steps. Write a few lines test... add a line or two test...

More information

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

CS 61A Interpreters, Tail Calls, Macros, Streams, Iterators. Spring 2019 Guerrilla Section 5: April 20, Interpreters. CS 61A Spring 2019 Guerrilla Section 5: April 20, 2019 1 Interpreters 1.1 Determine the number of calls to scheme eval and the number of calls to scheme apply for the following expressions. > (+ 1 2) 3

More information