[公开课] CS61A打卡Spring2018(week1-week8): Structure and Interpretation of Computer Programs

想问的问题:

  1. HW3: Q2 pingpong: helper function
  2. HW3: Q7 anonymous factorial
  3. Disc4:
    >>>[[y * 2 for y in [x, x + 1]] for x in [1, 2, 3, 4]]
    [[2, 4], [4, 6], [6, 8], [8, 10]]
  4. Lab5: Q7*
  5. Disc5:
    >>> lst3 = lst2[:]
    >>> lst3 is lst2
    False
  6. HW5:Q4
  7. HW6: Q1
  8. Lab6: Note: You might run into trouble when you mutate a list as you’re iterating through it. Try iterating through a copy instead! You can use slicing to copy a list:
    lst = [2, 2, 2, 2]
    for element in lst:
       if element == 2:
           lst.remove(element)
    length = len(lst) # length = 2
    
    v.s.
    lst = [2, 2, 2, 2]
    for element in lst[:]:
    	if element == 2:
    		lst.remove(element)
    length = len(lst) #length = 0
    
    Lab6: Q10

2019 Spring: https://cs61a.org
2018 Spring: http://inst.eecs.berkeley.edu/~cs61a/sp18/
计算机程序的构造和解释 (SICP) http://www-mitpress.mit.edu/sicp/full-text/book/book.html
如果想要SICP的书中的练习答案可以到 http://eli.thegreenplace.net/

Lab 2 - 6: 2, 4, 5
Disc 2- 6: 2, 3, 4, 5, 6
HW 2 - 5: 2, 3, 4, 5, 6
Guerrilla 0 - 2: 1(today)
Extra:
Midterm Exam/ Review
Project

  • Project 1: Hog - related videos: 2/23 Lecture 15 Video 1

  • Project 2: Yelp Maps

  • Project 3: Ants Vs. SomeBees

  • Extra 1

  • Extra 2

  • HW 1, 2, 3, 4, 5 (Long)
    2/20

  • Spring 2018 Midterm 1 2/8

  • Week 1 (1/15-1/19) : Functions, Names, and Python Basics

  • Week 2 (1/22-1/26) : Control, High-Order Functions, and Environments

  • Week 1&2 : Disc, Lab, HW, Project, Guerrilla

  • Extra 1 (1/24) : Newton Method

  • Week 3 (1/29-2/2) : Iteration, Recursion, Tree Recursion

  • Week 4 (2/5-2/9) : Function Examples, * Midterm 1, Data Abstraction

  • Week 5 (2/12-2/16) : Containers, Trees, Mutable Values

  • Week 6 (2/19-2/23) : Mutable Functions, Objects

  • Week 7 (2/26-3/2) : Inheritance, Representation, Growth

  • Week 8 (3/5-3/9) : Composition, Ordered Sets, Tree Sets

(新的甘特图功能,丰富你的文章)

Mon 07 Mon 14 Mon 21 Mon 28 Mon 04 Mon 11 Mon 18 Mon 25 Mon 04 Mon 11 Mon 18 Mon 25 April Mon 08 Completed task week 1 and week 2 week 1 and week 2 week 1 and week 2 Future task in critical line Create tests for renderer Add to mermaid Total tasks A Gantt Diagram for UCB CS61A
  • 关于 甘特图 语法,参考 [这儿][2]

CS61A(2018 video with 2019 HW)

  • Week 1 (1/15-1/19) : Functions, Names, and Python Basics

    • Expressions: (Primitive expressions; Call expressions (Operator and Operand); )
    • Names, Assignment, and User-Defined Functions;
    • Environment Diagrams;
    • Defining Functions: (function signature; function body; Calling User-Defined Functions; Looking Up Names In Environments)
      - An environment is a sequence of frames.
      - A name evaluates to the value bound to that name
    • Life Cycle of a User-Defined Function:
      - Def statement
      - Call expression
      - Calling/Applying
  • Week 2 (1/22-1/26) : Control, High-Order Functions, and Environments

    • Print and None: None Indicates That None Is Returned; Pure Functions & Non-Pure Functions; Nested Expressions with Print;
    • Multiple Environments: Names Have Different Meanings in Different Environments;
    • Miscellaneous Python Features
      • -i; -m doctest (“m” stands for “module”); default value.
    • Statements: Compound Statement (Header; Clause; Suite); Conditional Statement; Boolean Contexts;
    • Iteration: While Statement; The Fibonacci sequence;
    • Designing Functions:
      • Characteristics of Functions
        • A function’s domain is the set of all inputs it might possibly take as arguments.
        • A function’s range is the set of output values it might possibly return.
        • A pure function’s behavior is thE relationship it creates between input and output.
      • A Guide to Designing Functions:
        • Give each function exactly one job.
        • Don’t repeat yourself. Implement a process just once, but execute it many times.
        • Define functions generally.
    • Higher-Order Functions (A function that takes a function as an argument value or returns a function as a return value)
      • Generalization
        • Generalizing Patterns with Arguments.
        • Generalizing Over Computational Processes.
      • Functions as Return Values
        • Functions defined within other function bodies are bound to names in a local frame.
        • Call Expressions (调用表达式) as Operator Expressions.
      • The purpose of Higher-Order functions
        • Express general methods of computation
        • Remove repetition from programs
        • Separate concerns among functions
    • Lambda Expressions (are expressions that evaluate tow functions)
      • Lambda Expressions Versus Def Statements
        • Both create a function the same domain, range, and behavior.
        • Both functions have as their parent the frame in which they were defined.
        • Both bind that function to the name square.
        • *Only the def statement gives the function an intrinsic name.
    • Environments Enable Higher-Order Functions
    • Environments for Nested Definitions
      • How to Draw Environment Diagram
    • Local Names
    • Function Composition
  • Week 1&2 : Disc, Lab, HW, Project, Guerrilla

    • HW1: Q4
      The function with_if_function uses a call expression, which guarantees that all of its operand subexpressions will be evaluated before if_function is applied to the resulting arguments.
      Therefore, even if c returns False, the function t will be called. When we call t, we print out 1. Then, when we call f, we will also print 2.
      By contrast, with_if_statement will never call t if c returns False. Thus, we will only call f, printing 2.
    • Lab1: Q1: Infinite Loop
      >>> n = 3
      >>> while n >= 0:
      ... n -= 1
      ... print(n)
    • Lab1: Q2: What would python display?(WWPD)
      >>> True and 13
      13
      >>> False or 0
      0
      >>> not 10
      False
      >>> not None
      True
      >>> True or 1 / 0 or False
      True
      >>> 0 or False or 2 or 1 / 0
      2
      >>> (1 + 1) and 1
      1
      >>> 1/0 or True
      Error
    • Disc1: Boolean Operators
      Python also includes the boolean operators and, or, and not. These operators are used to combine and manipulate boolean values.
      • not returns the opposite truth value of the following expression.
      • and stops evaluating any more expressions (short-circuits) once it reaches the first false value and returns it. If all values evaluate to a true value, the last value is returned.
      • or short-circuits at the first true value and returns it. If all values evaluate to a false value, the last value is returned.
  • Extra 1 (1/24) : Newton Method

    • Newton Method
  • UNIX commands

    • Directories:
      • ls: list the files and folders inside of the current directory
      • mkdir: make a new directory. For example, mkdir example creates a directory called example
      • cd: change directories. For example, cd example changes directories to example
      • rm -r: recursively remove a specified directory. For example, rm -r example removes the example directory and all files and subdirectories inside it.
    • Files:
      • cat: displays the contents of a file on the screen. For example, cat unix.txt shows the contents of the file unix.txt
      • mv: moves a file/directory to another file/directory. For example, mv file1 file2 moves the contents of file1 into a (possibly new) file called file2. When moving one file to another, we are effectively renaming the file!
      • cp: copies a file to another file/directory. For example, cp file1 file2 copies the contents of file1 into a file named file2.
      • rm: removes a file. For example, rm file1 deletes the file called file1.
    • Miscellaneous:
      • echo: displays words on the screen
      • man: displays manual pages for a specified command
  • Week 3 (1/29-2/2) : Iteration, Recursion, Tree Recursion

    • Iteration Example: Fibonacci Numbers
    • Return
    • Self-Reference
    • Function Example: Sounds. (What the point of building higher-order functions?) Mario song.
    • Recursive Functions: A function is called recursive if the body of that function calls itself, either directly or indirectly.
      • The anatomy of a recursive function:
        • The def statement header is similar to other functions
        • Conditional statements check for base cases
        • Base cases are evaluated without recursive calls
        • Recursive cases are evaluated with recursive calls
    • Recursion in Environment Diagrams
    • Iteration vs Recursion
      • Iteration is a special case of recursion
      • Mathematical difference (factorial example)
    • Verifying Recursive Functions
      • The Recursive Leap of Faith
      1. Verify the base case.
      2. Treat fact as a fucntional abstraction!
      3. Assume that fact(n-1) is correct.
      4. VeRify that fact(n) is correct, assuming that fact(n-1) correct.
    • Mutual Recursion: When two different functions call each other
      • The Luhn Algorithm (credit card)
    • Recursion and Iteration
      • Converting Recursion to Iteration
        • Can be tricky: Iteration is a special case of recursion.
        • Idea: Figure out what state must be maintained by the iterative function.
      • Converting Iteration to Recursion
        • More formulaic: Iteration is a special case of recursion.
        • Idea: The state of an iteration can be passed as arguments.
    • Hog Guide!!!
    • Tree Recursion
      • Order of Recursive Calls
        • Two Definitions of Cascade: which one is better?
          • When learning to write recursive functions, put the base cases first.
          • If two implementations are equally clear, then shorter is usually better.
        • Inverse Cascade
      • Tree Recursion: tree-shaped processes arise whenever executing the body of a recursive function makes more than one call to that function.
        • Repetition in Tree-Recursive Computation
      • Example: Counting Partitions
        • Recursive decomposition: finding simpler instances of the problem.
        • Explore two possibilities:
          • Use at least one 4
          • Don’t use any 4
        • Solve two simpler problems:
          • count_partitions(2, 4)
          • count_partitions(6, 3)
        • Tree recursion often involves exploring different choices
  • Extra 2 (1/31) : Decisions

    • [x]
  • Week 4 (2/5-2/9) : Function Examples, * Midterm 1, Data Abstraction

    • Abstraction
      • Functional Abstractions
      • Choosing Names
        • Name should convey the meaning or purpose of the values to which they are bound.
        • The type of value bound to the name is best documented in a function’s docstring.
        • Function names typically convey their effect (print), their behavior (triple), or the value returned (abs).
        • Names can be long if they help document your code.
        • Names can be short if they represents generic quantities: counts, arbitrary functions, arguments to mathematical operations, etc.
      • Which Values Deserve a Name
        • Repeated compound expressions
        • Meaningful parts of complex expressions
    • Testing
      • Test-Driven Development
        • Write the test of a function before your write the function.
        • Develop incrementally and test each piece before moving on.
        • Run your code interactively.
    • Curring 柯里化
      • Function Currying: Transforming a multi-argument function into a single-arugment, higher-order function.
    • Decorators: example:trace
    • Review
      • What Would Python Print?
        • The print functoin returns None. It also displays its arguments (separated by spaces) when it is called.
        • A name evaluates to the value bound to that name in the earliest frame of the current environment in which that name is found.
    • Data Abstraction
      • Rational Numbers Arithmetic Implementation
    • Pairs
      • Representing pairs using lists
    • Abstraction Barriers
    • Data Representations
  • Week 5 (2/12-2/16) : Containers, Trees, Mutable Values

    • Lists
      • Working with Lists
        • The number of elements len
        • An element selected by its index
        • Concatenation and repetition
        • Nested lists
    • Containers
      • Built-in operators for testing whether an element appears in a compound value in(looks for individual element in the list, not subsequence) not in
    • For Statement
      • Sequence Unpacking in For Statements
    • Range: A range is a sequence of consecutive integers
      • The Range Type
        • Length: ending value - starting value
        • Element selection: starting value + index
    • List Comprehensions
    • Strings
      • Strings are an abstraction exec
      • String Literals Have Three Forms
        • Single-quoted and double-quoted strings are equivalent
        • Triple -quoted string can have multiple lines
      • Strings and Sequences
        • Length and element selection are similar to all sequences
        • However, the “in” and “not in” operators match substrings
    • Dictionaries {key1:value1, key2:value2,…}
      • Dictionaries are unordered collections of key-value pairs
      • .keys(); .values; dict(list)
      • dictionary comprehension
      • Limitations on Dictionaries
        • A key of a dictionary cannot be a list or a dictionary (or any mutable type)
        • Two keys cannot be equal
    • Box-and-Pointer Notation
      • The Closure Property of Data Types
      • Box-and-Pointer Notation in Environment Diagrams
    • Slicing (include the lower bound exclude the upper bound)
    • Processing Container Values
      • Sequence Aggregation
        • sum(iterable[, start]) -> value
        • max(iterable[, key=func]) -> value
          max(a, b, c, …[, key=func]) -> value
        • all(iterable) -> bool
        • mean; any; …
    • Trees
      • Tree Abstraction
        • Recursive description(wooden trees: root label, branches, leaf)
        • Relative description (family trees: node, root node, label, parent/child, siblings, ancestor, descendant)
        • Implementing the Tree Abstraction
    • Tree Processing (Function that take tree as input or return tree as output) 挺难的
      • Tree Processing Uses Recursion
      • Hint: If you sum a list of lists, you get a list containing the elements of those lists
        >>> sum([[1],[2,3],[4]],[])
        [1,2,3,4]
        >>> sum([ [[1]],[2] ],[])
        [[1], 2]
    • Creating Tree: A function that creates a tree from another tree is typically also recursive
    • Printing Tree
    • Objects:
      - attributes (bound to value)
      - methods: attributes bound to function
      • Objects represent information
      • They consist of data and behavior, bundled together to create abstractions
      • Objects can represent things, but also properties, interactino, & processes
      • A type of object is called a class; classes are first-class values in Python
      • Object-oriented programming:
        • A metaphor for organizing large programs
        • Special syntax that can improve the composition of programs
      • In Python, every value is an object
        • All objects have attributes
        • A lot of data manipulation happens thruogh object methdos
        • Functions ado one thing; objects do many related things
    • Example: Strings
      • Representing Strings: the ASCII Standard
      • Representing Strings: the Unicode Standard
    • Mutation Operations
      • Some Objects Can Change (its value over time)
        • All names that refer ot the same object are affected by a mutation
        • Only objects of mutable types can change: lists & dictionaries
      • Mutation Can Happen Within a Function Call
        • A function can change the value of any object in its scope
    • Tuples
      • Tuples are immutable sequences
        • Immutable values are protected from mutation (cannot change value but binding can be changed)
        • Please distinguish object mutation from name change!!!
        • The value of an expression can changbe cause of changes in names or objects
        • An immutable sequence may still change if it contians a mutable value as an element
    • Mutation
      • Sameness and Change
      • Identity Operator
        • Identity <exp0> is <exp1> if True then same
        • Equality <exp0> == <exp1> if True then equal
        • Identical objects are always equal values
        • Mutable default Arguments are Dangerous
          • A default argument value of part fo a function value, not generated by a call
  • Week 6 (2/19-2/23) : Mutable Functions, Objects

    • Mutable Functions
      • A Function with Behavior That Varies Over Time
      • Persistent Local State Using Environments
      • Reminder: Local Assignment
        • Execution rule for assignment statements:
        1. Evaluate all expressions right o f-, from left to right
        2. Bind the names on the left to the resulting values in the current frame.
      • Non-Local Assignment & Persistent Local State nonlocal
        • The Effect of Nonlocal Statements
          • Effect: Future assignments to that name change its ore-existing binding in the first non-local (Python Docs: an “enclosing scope”) frame of the current environment in which that name is bound.
        • Python Particulars
          • Python pre-computes which frame contains each name before executing the body of a function.
          • Within the body of a function, all instances of a name must refer to the same frame.
            // An highlighted block
            def make_withdraw(balance):
            	def withdraw(amount):
            		# nonlocal balance
            		if amout > balance:
            			return 'Insufficient funds'
            		balance = balance - amount
            		return balance
            	return withdraw
            
            >>> w = make_withdraw(100)
            >>> w(10)
            UnboundLocalError: local variable 'balance' referenced before assignment
      • Mutable Values & Persistent Local State
        • Mutable values (list & dictionary) can be changed without a nonlocal statement.
    • Multiple Mutable Functions
      • Referential Transparency, Lost
        • Expressions are referentially transparent if sbustituting an experssion with its value does not change the meaning of a program.
        • Mutation operations violate the conditio nof referential transparency because they do more than just return a value; they change th eenvironment.
      • Environment Diagrams includes lists and nonlocal assignment statements.
    • Object-Oriented Programming
      • OOP:
        • A method for organizing modular programs
          • Abstraction barriers
          • Bundling together information and related behavior
        • A metaphor for computation using distributed state
          • Each object has its own local state.
          • Each object also knows how to manage its own local state, based on method calls.
          • Method class are messages passed between objects.
          • Several objects may all be instances of a common type.
          • Different types may relate to each other.
        • Specialized syntax & vocabulary to support this metaphor
    • Classes: A class serves as template for its instances
      • The Class Statement: class <name>: // <suite>
        • A class statement creates a new class and binds that class to <name> in the first frame of the current environment.
        • Assignment & def statemtens in <suite> create attributes of the class (not names in frames).
        • The suite is executed when the class staetment is executed.
      • Obejct Construction:
        • When a class is called:
        1. A new instance of that class is created
        2. The _init_ method of the class is called with the new object as its first argument (named self), along with any additional arguments provided in the call expression. (init is called a constructor, so you can see the relationship between data abstraction and the object-oriented programming with python)
      • Obejct Identity:
        • Every object that is an instance of a user-defiend class has a unique identity
        • Identity operators “is” and “is not” test if two expressions evaluate to the same object
        • Binding an object to a new name using assignment does not create a new object
    • Methods
      • Methods are defined in the suite of a class statement. These def statements create function objects as always, but their names are bound as attributes of the class.
      • Invoking Methods:
        • All invoked methods have access to the object via the self parameter, and soh they can all access and manipulate the object’s state.
        • Dot notiaton automatically supplies the first argument to a method.
      • Dot Expressions:
        • Objects receive messages via dot notation.
        • Dot notation accesses attributes of the instance or its class.
      • Attributes
        • getattr and dot expressions look up a name in the same way
      • Methods and Functions
        • Python distinguishes between
          • Functions, which we have been creating since the beginning of the course, and
          • Bound methods, which couple together a function and the object on which that method will be invoked.
      • Looking Up Attributes by Name
        • <expression>.<name>
        • To evaluate a dot expression:
        1. Evaluate the <expression> to the left of the dot, which yields the object of the dot expression.
        2. <name> is matched against the instance attributes of that object; if an attribute with that name exists, its value is returned.
        3. If not, <name> is looked up in the class, which yields a class attribute value.
        4. That value is returned unless it is a function, in which case a bound method is returned instead.
      • Class Attributes
        • Class attributes are “shared” across all instances of a class because they are attributes of the class, not the instance.
  • Week 7 (2/26-3/2) : Inheritance, Representation, Growth

    • Attribute Assignment
      • Assignment statements with a dot expression on their left-hand side affect attributes for the object of that dot expression.
        • If the object is an instance, then assignment sets an instance attribute
        • If the object is a class, then assignment sets a class attribute
    • Inheritance: A method for relating classes together
      • A common uses: Two similar classes differ in their degree of specialization
    • Looking Up Attribute Names on Classes
      • Base class attributes aren’t copied into subclasses
      • To look up a name in a class:
      1. If it names an attribute in the class, return the attribute value.
      2. Otherwise, look up the name in the base class, if there is none.
    • Object-Oriented Design
      • Don’t repeat yourself, use existing implementations, try to avoid copying and pasting code.
        • Attributes that have been overridden are still accessible via class objects.
        • Look up attributes on instances whenever possible.
      • Inheritance and composition
        • OOP shines when we adopt the metaphor.
        • Inheritance is best for representing is-a relationships.
        • Composition is best for representing has-a relationships.
    • Attributes Lookup Practice (Important)
    • Multiple Inheritance: A subclass has multiple base classes
    • Complicated Inheritance (Warning): Multiple Inheritance should be rarely used!
    • String Representations
      • In python, all objects produce two string representations
        • The str is legible to humans
        • The repr is legible to the Python interpreter
        • The str and repr are often the same, but not always.
      • The repr String for an Object
        • The repr function returns a Python expression (a string) that evaluates to an equal object
        • The result of calling repr of calling repr on a value is what Python prints in an interactive session
        • Some objects do no thave a simple Python-readable string
      • The str String for an Object
        • Human interpretable strings are useful as well
        • The result of calling str on the value of an expression is what Python prints using the print function.
    • Polymorphic Functions:
      • A function that applies to many (poly) different forms (morph) of data
        • str and repr are both polymorphic; they apply to any object
        • repr invokes a zero-argument method __repr__ on its argument
        • str invokes a zero-argument method __str__ on its argument
      • Implement repr and str
    • Interfaces
      • Message passing: Objects interact by looking up attritbues on each other (passing messages)
      • The attribute look-up rules allow different data types to respond to the same message
      • A shared message (attribute name) that elicits similar behavior from different object classes is a powerful method of abstractoin
      • An interface (媒介, 中介) is a set of shaerd messages, along with a specification of what they mean
    • Special Method Names
      • Certain names are special because they have built-in behavior
      • These names always start and end with two underscores
      • __init__,__repr__,__add__,__bool__,__float__ refer to python docs
      • Special Methods: Adding instances of user-defined classes invokes either the __add__ or __radd__ method
    • Measuring Efficiency
    • Memoization
      • Idea: Remember the results that have been computed before
    • Space
      • The Consumption of Space
    • Time
      • The Consumption of Time
    • Order of Growth
    • Exponentiation
    • Properties of Orders of Growth
      • Nesting
      • Exponential growth, Quadratic growth, Linear growth, Square root growth, Logarithmic growth, Constant
  • Week 8 (3/5-3/9) : Composition, Ordered Sets, Tree Sets

    • Linked Lists
      • Linked List Structure
    • Property Methods
    • Tree Class
    • Tree Mutation(Example: Pruning Trees)
    • Sets (built-in Python container type)
      • Implementing Sets (assuming they are not built-in)
    • Set Operations
    • Set Mutation
    • Tree Sets
    • Tree
    • Binary Search and Binary Search Trees (balanced_bst, largest, second)
    • Sets as Binary Search Trees (contains, adjoin)

猜你喜欢

转载自blog.csdn.net/madao_yw/article/details/88323956