from operator import add, sub
def a_plus_abs_b(a, b):
"Return a+abs(b), but without calling abs.
> a_plus_abs_b(2, 3)
5
> a_plus_abs_b(2, 3)
5
"
if b < 0:
f = sub
else:
f = add
return f(a, b)
def two_of_three(a, b, c):
"Return x*x + y*y, where x and y ar
def multiple(a, b):
"Return the smallest number n that is a multiple of both a and b.
> multiple(3, 4)
12
> multiple(14, 21)
42
"
factorsa = []
factorsb = []
for x in range (1,a+1,1):
if a%x = 0:
factorsa.append(x)
for y in range (1,b+1,1):
if b%y = 0:
fa
Lecture #17: Abstraction Support: Exceptions,
Operators, Properties
Failed preconditions
Part of the contract between the implementor and client is the set
of preconditions under which a function, method, etc. is supposed
to operate.
Example:
class Rati
Lecture #20: Tree Recursions, Memoization, Tree
Structures
Example: Escape from a Maze
Consider a rectangular maze consisting of an array of squares some
of which are occupied by large blocks of concrete:
14
13
12
11
10
9
8
7
6
5
4
3
2
1
0
0
1
2 3 4 5 6
Lecture #22: Search Trees and Sets, Part II
Adding (Adjoining) a Value
Must add values to a search tree in the right place: the place
tree_find would try to find them.
For example, if we add 17 to the search tree on left, we get the one
on the right:
7
class Tree:
"A Tree consists of a label and a sequence
of 0 or more Trees, called its children."
def _init_(self, label, *children):
"A Tree with given label and children."
self._label = label
self._children = list(children)
@property
def is_leaf(self):
r
class Tree:
"A Tree consists of a label and a sequence
of 0 or more Trees, called its children."
def _init_(self, label, *children):
"A Tree with given label and children."
self._label = label
self._children = list(children)
@property
def is_leaf(self):
r
Lecture #21: Search Trees, Sets
General Tree Class (From Last Lecture)
class Tree:
"A Tree consists of a label and a sequence
of 0 or more Trees, called its children."
def _init_(self, label, *children):
"A Tree with given label and children."
def _str_(s
Lecture #15: OOP
Extending the Mutable Objects: Classes
Public Service Announcement: [email protected] will be hosting a
HackJam this Saturday
Lowpressure hackathon for both experienced makers and newbies.
Weve seen a variety of builtin mutable types (s
Lecture #18: Complexity and Orders of Growth
A Direct Approach
Certain problems take longer than others to solve, or require more
storage space to hold intermediate results.
We refer to the time complexity or space complexity of a problem.
But what doe
def near(L, x, delta):
"True iff X differs from some member of sequence L by no
more than DELTA."
for y in L:
if abs(xy) <= delta:
return True
return False
def is_unduplicated(L, pred):
"True iff the first x in L such that pred(x) is not
a duplicate. Als
from functools import reduce
from operator import add
def solve_maze(row0, col0, maze):
"Assume that MAZE is a rectangular 2D array (list of lists) where
maze[r][c] is true iff there is a concrete block occupying
column c of row r. ROW0 and COL0 are the i
Lecture #14: Mutable Data, Lists, and Dictionaries
Local, Global, and Nonlocal
By default, an assignment in Python (including = and for.in), binds
a name in the current environment frame (creating an entry if needed).
But within any function, one may de
class Tree:
"A Tree consists of a label and a sequence
of 0 or more Trees, called its children."
def _init_(self, label, *children):
"A Tree with given label and children."
self._label = label
self._children = list(children)
@property
def is_leaf(self):
r
Lecture #19: Complexity and Orders of Growth, contd.
The Notation
Suppose that f is a oneparameter function on real numbers.
O(f ): functions that eventually grow no faster than f :
g O(f ) means that g(x) Cg f (x) for all x Mg
where Cg and Mg ar
CS61A Lecture #28: The Halting Problem and
Incompleteness
The Halting Problem
An interpreter (or compiler) is a program that operates on programs.
In fact, there are numerous other ways to operate on programs. For
example,
Given a oneparameter functio
Lecture 27: Anatomy of an Interpreter
Last modified: Mon Apr 7 13:57:29 2014
CS61A: Lecture #27
1
Interpreting Scheme
Your project will have a structure similar to the calculator:
Split input into tokens, which are themselves Scheme values.
Parse the t
Lecture #24: Programming Languages and Programs
Metalinguistic Abstraction
A programming language is a notation for describing computations
Weve created abstractions of actionsfunctionsand of things
classes.
or processes.
These range from lowlevel not
Lecture #25: Calculator
Adminitrivia
Extended TA office hours in labs Tuesday from 11AM.
Exam is at 8PM on Wednesday; rooms to be assigned as happened
last time (not the same rooms: see postings and email to come).
No lecture on Wednesday, but Ill be i
class Range:
def _init_(self, low, high):
self._low = low
self._high = high
def _iter_(self):
return self._generate()
def _generate(self):
i = self._low
while i < self._high:
yield i
i += 1
class LetterIter:
"An iterator over letters.
> a_to_c = LetterIte
Lecture 27: Anatomy of an Interpreter
Interpreting Scheme
Your project will have a structure similar to the calculator:
Split input into tokens, which are themselves Scheme values.
Parse the tokens into Scheme expressions, which are also Scheme
values.
Lecture #26: Announcements
Scheme and Scheme Interpretation
Project 1 revisions: due April 10.
Hackathon: There is a hackathon hosted by [email protected] Hackvs. Stanford this Weekend. Prizes include: Macbook Airs, Retina iPads, Occulus
Rifts, Pebble Smartwatches.
Lecture #26: Announcements
Project 1 revisions: due April 10.
Hackathon: There is a hackathon hosted by [email protected] Hackvs. Stanford this Weekend. Prizes include: Macbook Airs, Retina iPads, Occulus
Rifts, Pebble Smartwatches. You dont need to have hackathon e
Lecture #23: Iterators on Trees
Slight Correction from Last Time
In the last lecture, I defined
class BinTree(Tree):
def _iter_(self): return tree_iter(self)
However, there is already an _iter_ method on BinTree, inherited
from Tree, which iterates over
Lecture #25: Calculator
A Sample Language: Calculator
Adminitrivia
Source: John Denero.
Extended TA office hours in labs Tuesday from 11AM.
Prefix notation expression language for basic arithmetic Pythonlike
Exam is at 8PM on Wednesday; rooms to be a
def desc_time(expr, setup=", number=1000):
time = 1e6 * min(timeit.repeat(expr, setup, number=number) / number
return "cfw_ loops, best of 3: cfw_:.2g usec per loop"\
.format(number, int(time)
def find_first(L, p):
"The index of the first item in list L t
Lecture #16: Inheritance and Interfaces
Inheritance
Classes are often conceptually related, sharing operations and behavior.
One important relation is the subtype or isa relation.
Examples: A car is a vehicle. A square is a plane geometric figure.
Wh
Higher Order Functions and Environment Diagrams
Instructions: Form a group of 45. Start on problem 0. Check off with a lab assistant when you
think everyone in your group understands how to solve problem 0. Repeat for problem 1, 2, .
You're not allowed t
Midterm 2
Review
1.
List Mutation
lets list some things you can do with lists
new list
mutates
list(lst)
lst.extend([7])
lst = lst + [7]
lst.append(7)
lst[:]
lst += [7]
lst.pop()

you can pop at a specific index

.pop() returns the item it removes
ls =
Higher Order Functions and Environment Diagrams
Instructions: Form a group of 45. Start on problem 0. Check off with a lab assistant when you
think everyone in your group understands how to solve problem 0. Repeat for problem 1, 2, .
You're not allowed t
* if you didnt bring a notebook, take 23 pieces of blank paper
* also take donuts :)
Discussion 4:
MT1 Review
Section: 115, CS Scholars
TA: Tammy Nguyen ([email protected])
Announcements
Project 4 due Friday, 08/05
1 EC for final submission by