CS 61 A (2022 Fall&2020 Fall)

CS 61 A (2022 Fall&2020 Fall)

As we all know ,most of the courses that most internal colleges have ,are so depressing for those who really want to learn some thing and do not realize the truth :The content is out of date ,the talk in class is boring ,the material for extra or inner is one-dimensional and thin .Finally ,you'll discover that you have made little progress during the whole four years learning .Especially in the area of CS ,we are lack of coding ,the experience of projects ,the reading of papers and blocks .

But thanks to the internet and those sharers ,we can easily get to the course from the best universities over the world ,you will find ,that you are not intelligent , you are not genius and you are not lazy or clumsy . We are just short of some right education to open our sight and encourage our spirit.

OK , let's back to the topic of CS61A , from UC Berkeley using Python and SQL ,it's good for those who have fundamentals in CS to get start with Python . My plan is to combine two semesters of the same course (mainly focus on 2020)which can make up my lack of memory.

And before we actually start,there is one last thing .Why choose EN to note this self-study journey? Not because it seems like magnificent , but because it's the prerequisite to learn CS , the key to reach broader learning space .

If you want to check a better realization of the lab or project ,or just look for details in chines you can follow this:日拱一卒,伯克利牛叉,这是我见过最酷炫的Python作业 - 腾讯云开发者社区-腾讯云 (tencent.com)

Schedule

Date Lecture Textbook Orientation Links Lab and Discussion Links Homework & Project
Wed 8/26 Computer Science Video full 1pp 8pp 01.py 2pm 2pm-NPE 6pm 7pm-NPE 9pm Lab 00: Getting Started
Fri 8/28 Functions Video Q&A full 1pp 8pp 02.py Ch. 1.1 Ch. 1.2 HW 01: Variables & Functions, ControlThu 9/3
Mon 8/31 Control Video Q&A full 1pp 8pp 03.py Ch. 1.3Ch. 1.4Ch. 1.5 2pm 2pm-NPE 6pm 7pm-NPE 9pm Lab 01: Variables & Functions, ControlTue 9/1
Wed 9/2 Higher-Order Functions Video Q&A full 1pp 8pp 04.py Ch. 1.6 2pm 2pm-NPE 6pm 7pm-NPE 9pm Disc 01: Environment Diagrams, Control HogFri 9/11
Fri 9/4 Environments Video Q&A full 1pp 8pp 05.py Ch. 1.6 2pm 2pm-NPE 6pm 7pm-NPE 9pm Lab 02: Higher-Order Functions, Lambda ExpressionsTue 9/8
Mon 9/7 No Lecture: Labor Day
Wed 9/9 Design Video Q&A full 1pp 8pp 06.py 2pm 2pm-NPE 6pm 7pm-NPE 9pm Disc 02: Higher-Order Functions, Self Reference
Fri 9/11 Function Examples Video Q&A full 1pp 8pp 07.py
Mon 9/14 Midterm 1
Wed 9/16 Recursion Video Q&A full 1pp 8pp 08.py Ch. 1.7 2pm 2pm-NPE 6pm 7pm-NPE 9pm Disc 03: Recursion Hog ContestMon 9/21
Fri 9/18 Tree Recursion Video Q&A full 1pp 8pp 09.py Ch. 1.7 HW 02: RecursionThu 9/24
Mon 9/21 Containers Video Q&A full 1pp 8pp 10.py Ch. 2.1Ch. 2.3 2pm 2pm-NPE 6pm 7pm-NPE 9pm Lab 04: Recursion, Tree Recursion, Python ListsTue 9/22
Wed 9/23 Data Abstraction Video Q&A full 1pp 8pp 11.py Ch. 2.2 2pm 2pm-NPE 6pm 7pm-NPE 9pm Disc 04: Tree Recursion, Python Lists, Data Abstraction CatsFri 10/2
Fri 9/25 Trees Video Q&A full 1pp 8pp 12.py Ch. 2.3
Mon 9/28 Binary Numbers (optional) Video Q&A full 2pm 2pm-NPE 6pm 7pm-NPE 9pm Lab 05: Data Abstraction, TreesTue 9/29
Wed 9/30 Circuits (optional) Video Q&A full 2pm 2pm-NPE 6pm 7pm-NPE 9pm Disc 05: Trees, Binary Numbers
Fri 10/2 Mutable Values Video Q&A full 1pp 8pp 15.py Ch. 2.4 HW 03: Trees, Data AbstractionThu 10/8
Mon 10/5 Mutable Functions Video Q&A full 1pp 8pp 16.py Ch. 2.4 2pm 2pm-NPE 6pm 7pm-NPE 9pm Lab 06: Nonlocal, MutabilityTue 10/6
Wed 10/7 Iterators Video Q&A full 1pp 8pp 17.py Ch. 4.2 2pm 2pm-NPE 6pm 7pm-NPE 9pm Disc 06: Nonlocal, Mutability, Iterators
Fri 10/9 Objects Video Q&A full 1pp 8pp 18.py Ch. 2.5 HW 04: Nonlocal, IteratorsThu 10/15
Mon 10/12 Inheritance Video Q&A full 1pp 8pp 19.py Ch. 2.5 2pm 2pm-NPE 6pm 7pm-NPE 9pm Lab 07: Object-Oriented Programming, IteratorsTue 10/13 AntsFri 10/23
Wed 10/14 Representation Video Q&A full 1pp 8pp 20.py Ch. 2.7 2pm 2pm-NPE 6pm 7pm-NPE 9pm Disc 07: Object-Oriented Programming
Fri 10/16 Composition Video Q&A full 1pp 8pp 21.py Ch. 2.9 HW 05: Object-Oriented Programming, Linked Lists, TreesMon 10/26
Mon 10/19 Efficiency (optional) Video Q&A full 1pp 8pp 22.py 22.ipynb Ch. 2.8 2pm 2pm-NPE 6pm 7pm-NPE 9pm Lab 08: Linked Lists, Mutable TreesTue 10/20
Wed 10/21 Decomposition Video Q&A full 1pp 8pp 23.py 23.zip 2pm 2pm-NPE 6pm 7pm-NPE 9pm Disc 08: Linked Lists, Trees, Representation
Fri 10/23 Data Examples Video Q&A full 1pp 8pp 24.py
Sat 10/24 Lab 09: Midterm ReviewTue 10/27
Mon 10/26 Users (optional) Video Q&A 2pm 2pm-NPE 6pm 7pm-NPE 9pm
Wed 10/28 Midterm 2
Fri 10/30 Ethical AI & Data (optional) Video
Mon 11/2 Scheme Video Q&A full 1pp 8pp 27.scm Ch. 3.1Ch. 3.2 2pm 2pm-NPE 6pm 7pm-NPE 9pm Lab 10: SchemeWed 11/4 HW 06: SchemeThu 11/5
Wed 11/4 Exceptions Video Q&A full 1pp 8pp 28.py Ch. 3.3 2pm 2pm-NPE 6pm 7pm-NPE 9pm Disc 10: Scheme, Scheme Lists
Fri 11/6 Calculator Video Q&A full 1pp 8pp 29.scm 29.zip Ch. 3.4 HW 07: Scheme ListsThu 11/12
Mon 11/9 Interpreters Video Q&A full 1pp 8pp Ch. 3.5 2pm 2pm-NPE 6pm 7pm-NPE 9pm Lab 11: InterpretersTue 11/10 SchemeTue 11/24 Scheme Challenge VersionTue 11/24
Wed 11/11 No Lecture: Veterans Day Disc 11: Interpreters
Fri 11/13 Declarative Programming Video Q&A full 1pp 8pp 31.sql Ch. 4.3 HW 08: SchemeThu 11/19
Mon Tables Video Q&A full 1pp 8pp 32.sql 2pm 2pm-NPE 6pm 7pm-NPE 9pm
Wed 11/18 Aggregation Video Q&A full 1pp 8pp 33.sql Ch. 4.3 2pm 2pm-NPE 6pm 7pm-NPE 9pm Disc 12: SQL
Fri 11/20 Databases (optional) Video Q&A full 1pp 8pp 34.py 34.sql Ch. 4.3 HW 09: SQLThu 12/3
Mon 11/23 Tail Calls (optional) Video Q&A full 1pp 8pp 2pm 2pm-NPE 6pm 7pm-NPE 9pm Lab 13: More SQLTue 11/24
Wed 11/25 No Lecture: Thanksgiving
Fri 11/27 No Lecture: Thanksgiving
Mon 11/30 Macros (optional) Video Q&A full 1pp 8pp 36.scm 2pm 2pm-NPE 6pm 7pm-NPE 9pm Lab 14: Final ReviewTue 12/1
Wed 12/2 Final Examples Video Q&A full 1pp 8pp 37.py 2pm 2pm-NPE 6pm 7pm-NPE 9pm Disc 14: Final Review
Fri 12/4 Conclusion Video Q&A HW 10: FinaleSun 12/13 Scheme GallerySun 12/13
Thu 12/17 Final (3-6 PM)

Task List

Lab

Home Work

Projects

Week 1

1. Lecture :Computer Science

It's just an introduction ,but if you are interested ,I suggest you watching or listening it.

Some records :

There is this notion, i think, that learning happens when you solve the problem.
That is completely wrong.
Learning happens when you don't solve the problem.
When you are struggling through.
When you have solved the problem, you've learned it.
It's over, right? So the the process of failure, the process of struggling, the process of taking hours to solve something is where the learning is happening.
The purpose of this course is for you to learn something you don't already know, not just to prove that you already know something.
You don't need a course for that.
You just need an exam for that.

Lab 0

Just configure your environment according to the introduction.

Lab 0: Getting Started | CS 61A Fall 2020 (berkeley.edu)

In my case ,I have installed Python and Git before ,so I just started at Git-Bash.

Because I didn't choose "Use Windows' default console window" option ,so I had to type winpty python to run the python .

Thanks to the teacher of my Operation System course ,I can use the terminal in Win & Linux expertly.

The Introduction of the using of terminal and python is so detailed that there is no need for me to repeat.

The lab00 is easy and do not waste your time on it .And there is no need for you to submit the answer.

2. Lecture :Functions

Videos

I think in general for learning computer science, videos are better than coming to a live lecture, because in live lecture if you miss something, then you might be confused for the rest of the hour.

It seems like he doesn't fear of making mistake or be rewound for times.

Home Work 1

It's truly depressing for me to take nearly 20 mins to solve those stupid mistakes.

  • It's interesting that I have never think about the situation that with_if_statement could be different with if
...
def if_function(condition, true_result, false_result):
    if condition:
        return true_result
    else:
        return false_result

def with_if_statement():
    if cond():
        return true_func()
    else:
        return false_func()

def with_if_function():
    return if_function(cond(), true_func(), false_func())
def cond():
    return False
def true_func():
    print(42)
    return None
def false_func():
    print(47)
    return None
...

3. Lecture :Control

>>>print(print(1),print(2))
1
2
None None

Print is a function and its return is 'None' or to say there is no return

You can imagine the sequence :print(1)>>print(2)>>print(None,None)

Methods of Testing
Assertions
 assert fib(8) == 13, 'The 8th Fibonacci number should be 13'
Doctests
  • The first line of a docstring should contain a one-line description of the function, followed by a blank line. A detailed description of arguments and behavior may follow. In addition, the docstring may include a sample interactive session that calls the function
def sum_naturals(n):
        """Return the sum of the first n natural numbers.

        >>> sum_naturals(10)
        55
        >>> sum_naturals(100)
        5050
        """
        total, k = 0, 1
        while k <= n:
            total, k = total + k, k + 1
        return total
>>> from doctest import testmod
>>> testmod()
TestResults(failed=0, attempted=2)
  • Another mean:
>>> from doctest import run_docstring_examples
>>> run_docstring_examples(sum_naturals, globals(), True)
Finding tests in NoName
Trying:
    sum_naturals(10)
Expecting:
    55
ok
Trying:
    sum_naturals(100)
Expecting:
    5050
ok

Lab 1

...

Project Hog

There are too many unlock cases!

  • Lambda Expressions will be soon talked in the 1.6 Lecture.
# The use of lambda
f=lambda a,b:a*b
# Is the same as
def lam(a,b):
    return a*b

Q

  • Question 1 > Suite 1 > Case 5
>>> from hog import *
>>> counted_dice = make_test_dice(4, 1, 2, 6)
>>> roll_dice(3, counted_dice)
1
>>> # Make sure you call dice exactly num_rolls times!
>>> # If you call it fewer or more than that, it won't be at the right spot in the cycle for the next roll
>>> # Note that a return statement within a loop ends the loop
>>> roll_dice(1, counted_dice)
2

# Error: expected
#     6
# but got
#     2

Spend 15min to solve this confusing error

# Original Statement
    sum_roll=0
    for i in range(0,num_rolls):
        roll=dice()
        if roll==1:
        	return 1
        else:
        	sum_roll+=roll
     return sum_roll
# Passed
	sum_roll=0
    pig=False
    for i in range(0,num_rolls):
        roll=dice()
        if roll==1:
            pig=True
        else:
            sum_roll+=roll
    if pig:
        return 1
    else:
        return sum_roll
  • Question 6 > Suite 2 > Case 4

Do not forget other rules!

  • Question 6 > Suite 2 > Case 2
>>> def count(n):
...     def say(s0, s1):
...         print(n, s0)
...         return count(n + 1)
...     return say
>>> s0, s1 = play(always_roll(1), always_roll(1), dice=make_test_dice(5), goal=10, say=count(1))
# Error: expected
#     1 5
#     2 5
#     3 10
# but got
#     1 5
#     1 5
#     1 10

Stuck for 20min.....

# code
....
    while True:
        if score0>=goal or score1>=goal:
            break
        if who==0:
            score0+=take_turn(strategy0(score0,score1),score1,dice)
            say=say(score0, score1)		# Not just`say(score0,score1)`
            if pig_pass(score0, score1) or swine_align(score0,score1):
                continue
            else:
                who=1
                continue
        else:
            score1 += take_turn(strategy1(score1,score0), score0, dice)
            say=say(score0, score1)
            if pig_pass(score1,score0) or swine_align(score1,score0):
                continue
            else:
                who=0
                continue
....
  • Question 8 > Suite 2 > Case 2

Remember to add '.0' after your int number

  • Takes 3 hours to finish it

4. Lecture :Higher-Order Functions

Text :Ch1.6

  • Functions as Arguments

In python ,you can just think of functions as objects,so you can use it in arguments,return of another functions . It also can call and return itself.

But remember to keep one single function abstract,clear and simple enough for reading or using.

  • Functions as General Methods
def improve(update, close, guess=1):
        while not close(guess):
            guess = update(guess)
        return guess
def golden_update(guess):
        return 1/guess + 1
def square_close_to_successor(guess):
        return approx_eq(guess * guess, guess + 1)
def approx_eq(x, y, tolerance=1e-15):
        return abs(x - y) < tolerance
        
result=improve(golden_update, square_close_to_successor)        

What if we combine those functions as what we usually do ?

def combine(guess=1,tolerance=1e-15):
    while not abs(guess*guess-(guess+1))<tolerance:
        guess=1+1/guess
    return guess
print(combine())

It only can calculate the golden rate. In my opinion , it's ok when you are facing operation or solution. But if you are focus on the structure and logic ,it's better for you to divide it especially in a complex project.


So the way I think might be like:

I want to generate golden rate -> How? -> Use approach mean and run over and over again ->While trigger: guess= (1/guess + 1) ->This is infinite,but I want to to stop at a specific precision -> How? -> Give a tolerance and return True or False to trigger{Assume we already know that it can be computed by repeatedly summing the inverse of any positive number with 1, and that it is one less than its square. -> Compare guess * guessand guess + 1}-> How do you know the T or F? -> Use equal close -> x=y +/-tolerance -> abs(x - y) < tolerance


May not be necessary , but keep thinking the abstract of logic.

  • Defining Functions III: Nested Definitions

If you choose to combine the functions ,you have to pull down and rewrite all the logic ,but for divided ,you can frequently reuse the same functions.

def improve(update, close, guess=1):
        while not close(guess):
            guess = update(guess)
def approx_eq(x, y, tolerance=1e-15):
        return abs(x - y) < tolerance
def average(x, y):
	    return (x + y)/2  
def sqrt(a):
        def sqrt_update(x):
            return average(x, a/x)
        def sqrt_close(x):
            return approx_eq(x * x, a ,1e-3)
        return improve(sqrt_update, sqrt_close)
result = sqrt(256)
The sqrt_update function carries with it some data: the value for a referenced in the environment in which it was defined. Because they "enclose" information in this way, locally defined functions are often called `closures`.
  • Functions as Returned Values

This will be used in Hog,you can take a look of the operation step by step in python tutor.

  • Example: Newton's Method

(30条消息) 图文详解牛顿迭代法,牛顿不止力学三定律_Mr.Winter`的博客-CSDN博客

watch videos

  • Currying

OK,I have never used this kind of function until Hog

We can use higher-order functions to convert a function that takes multiple arguments into a chain of functions that each take a single argument. More specifically, given a function f(x, y), we can define a function g such that g(x)(y) is equivalent to f(x, y). Here, g is a higher-order function that takes in a single argument x and returns another function that takes in a single argument y. This transformation is called currying.
  • Lambda Expressions

Already mentioned

  • Abstractions and First-Class Functions
 As programmers, we should be alert to opportunities to identify the underlying abstractions in our programs, build upon them, and generalize them to create more powerful abstractions.  This is not to say that one should always write programs in the most abstract way possible;  expert programmers know how to choose the level of abstraction appropriate to their task.  But it is important to be able to think in terms of these abstractions, so that we can be ready to apply them in new contexts.
  • Function Decorators

As we(students of 2019)are talking about the decorators,we have to recommend the Project Practice course(mainly use Python) of He Fei for you . If you have enough interest and willingness,you can try to ask for participating in the project .Do not be disappointed if the work is not what you want, you have to try many things and finally you can find what you really love.


Use this to look through what the decorators do:

Online Python Tutor - Composing Programs - Python 3

After using the decorator on the Func ,when you are calling the Func , it will turn to the decorator-function ,and the reason why you can see the result of Func is that generally we will recall the Func in the decorator-function.

Video

Lab 2

Note: The answer can be Function/Error/Nothing

? It really confused me.

? 'cake'
-- Not quite. Try again! --

? 'cake'
-- OK! --

5. Lecture :Environments

6. Lecture :Design

7. Lecture :Function Examples

8. Lecture :Recursion

It takes too much time to note every thought during reading the Chapter like Ch1.6 , so I'll reduce some unnecessary note content.

Text :Ch1.7

If you have read any kinds of code books or learned any algorithm courses , Recursion will not be strange for you.


Penjee's gif is good for beginner to understand:

  • The Anatomy of Recursive Functions
Recursive functions express computation by simplifying problems incrementally.For example, summing the digits of 7 is simpler than summing the digits of 73, which in turn is simpler than summing the digits of 738.
we should not care about how fact(n-1) is implemented in the body of fact; we should simply trust that it computes the factorial of n-1. Treating a recursive call as a functional abstraction has been called a recursive leap of faith.
  • Mutual Recursion
def is_even(n):
    if n == 0:
        return True
    else:
        if (n-1) == 0:
            return False
        else:
            return is_even((n-1)-1)
>>> def play_alice(n):
        if n == 0:
            print("Bob wins!")
        else:
            play_bob(n-1)
>>> def play_bob(n):
        if n == 0:
            print("Alice wins!")
        elif is_even(n):
            play_alice(n-2)
        else:
            play_alice(n-1)
>>> play_alice(20)
Bob wins!
  • Printing in Recursive Functions
  • Tree Recursion
  • Example: Partitions

Imagine there is a tree with many leaves,every leaf means a situation that (n-m)->n<=0orm=0 .Each leaf will add 1 or 0 to the 'tree'.And all recursive will stop at one leaf .

>>> def count_partitions(n, m):
        """Count the ways to partition n using parts up to m."""
        if n == 0:
            return 1
        elif n < 0:
            return 0
        elif m == 0:
            return 0
        else:
            return count_partitions(n-m, m) + count_partitions(n, m-1)
>>> count_partitions(6, 4)
9

9. Lecture :Tree Recursion

Home Work 2

No idea at all

def next_largest_coin(coin):
    if coin == 1:
        return 5
    elif coin == 5:
        return 10
    elif coin == 10:
        return 25
def count_coins(total):   
   def helper(total, m):
        if total == 0:
            return 1
        elif total < 0:
            return 0
        elif m == None:
            return 0
        else:
            return helper(total - m, m) + helper(total, next_largest_coin(m))
    return helper(total, 1)

10. Lecture :Containers

Text :Ch2.1

  • Native Data Types
Python includes three native numeric types: integers (int), real numbers (float), and complex numbers (complex).
>>> type(1+1j)
<class 'complex'>

Lab4 after Lab2 ? Strange.

Lab :4

  • Maximum Subsequence
def max_subseq(n, t):
    if n == 0 or t == 0:
        return 0
    with_ones = max_subseq(n//10, t-1) * 10 + n%10
    not_with = max_subseq(n//10, t)
    if with_ones > not_with:
        return with_ones
    else:
        return not_with

Do not care the operation. Just focus that if it can make the seq to be max ,then add it and reduce t . If not ,just pass.

But if you really use pytutor to see how it works,you will find it is much more complex than how we handle it.

Simplify it

11. Lecture :Data Abstraction

Text :Ch2.2

  • Example: Rational Numbers
  • Pairs
>>> from operator import getitem
>>> pair = [10, 20]
>>> getitem(pair, 0)
10
  • Abstraction Barriers
>>> def pair(x, y):
        """Return a function that represents a pair."""
        def get(index):
            if index == 0:
                return x
            elif index == 1:
                return y
        return get
>>> def select(p, i):
        """Return the element at index i of pair p."""
        return p(i)

With this implementation, we can create and manipulate pairs.

>>> p = pair(20, 14)
>>> select(p, 0)
20
>>> select(p, 1)
14
  • The Properties of Data

Project cats

  • autocorrect

The title description is fuzzy:.It's better to have some hints.

"""Returns the element of VALID_WORDS that has the smallest difference
from USER_WORD. Instead returns USER_WORD if that difference is greater
than LIMIT."""

the smallestmeans that ,if there is the same word in valid_words ,just return it .After that we use diff_function to judge which one is smallest.

If you don't know this ,you may feel confused doing this case:

autocorrect('inside',['inner','inside'],first_same,0.5)
autocorrect('inside',['inner','insider'],first_same,0.5)
  • pawssible_patches

This is the subject that has been bothering me for quite some time .Main statement:

    if start[0] == goal[0]:
        next = pawssible_patches(start[1:], goal[1:], limit)

    else:
        add = 1 + pawssible_patches(start, goal[1:], limit - 1)
        remove = 1 + pawssible_patches(start[1:], goal, limit - 1)
        substitute = 1 + pawssible_patches(start[1:], goal[1:], limit - 1)

we should use recursion ,to generate a tree with every possibility

If not equal then add or remove or substitute

  • Problem 8

While unlock , you may find that though you typed the right anwser ,you can not pass it like this:(I don't know why)

(line 1)? ID: 1 Progress: 0.6
-- Not quite. Try again! --

(line 1)? ID: 1 Progress: 0.6
(line 2)? 0.6
-- OK! --
  • time_per_word

only usereturn game(words,time)can pass specific case

  • fastest_words

Again, using the helper functions provided in the following article can greatly reduce the workload

12. Lecture :Trees

Text :Ch2.3

13. Lecture :Binary Numbers

Lab :5

You can look at the helper methods before you write them, because if you write a bunch of redundant decision statements, it's better to call them in one line

  • find a brief and clear function from the web
def sprout_leaves(t, leaves):
    if is_leaf(t):
        return tree(label(t), [tree(leaf) for leaf in leaves])
    return tree(label(t), [sprout_leaves(s, leaves) for s in branches(t)])

14. Circuits (optional)

15. Mutable Values

Text :Ch2.4

  • The Object Metaphor
In fact, all values in Python are objects. That is, all values have behavior and attributes. They act like the values they represent.
  • Sequence Objects
>>> suits
['coin', 'cup', 'spade', 'club']
>>> suits[0:2] = ['heart', 'diamond']  # Replace a slice
>>> suits
['heart', 'diamond', 'spade', 'club']

With mutable data, methods called on one name can affect another name at the same time.

But,Lists can be copied using the list constructor function. Changes to one list do not affect another, unless they share structure.


While it is not possible to change which elements are in a tuple, it is possible to change the value of a mutable element contained within a tuple.

>>>nest = (10, 20, [30, 40])
>>>nest[2].pop()
40
  • Dictionaries

A useful method implemented by dictionaries is get, which returns either the value for a key, if the key is present, or a default value. The arguments to get are the key and the default value.

  • Local State
An implementation of make_withdraw requires a new kind of statement: a nonlocal statement. When we call make_withdraw, we bind the name balance to the initial amount. We then define and return a local function, withdraw, which updates and returns the value of balance when called.

This will be used in lab and home work

This pattern of non-local assignment is a general feature of programming languages with higher-order functions and lexical scope. Most other languages do not require a nonlocal statement at all. Instead, non-local assignment is often the default behavior of assignment statements.
  • The Benefits of Non-Local Assignment
def make_withdraw(balance):
	def withdraw(amount):
	        nonlocal balance
	        if amount > balance:
	            return 'Insufficient funds'
	        balance = balance - amount
		return balance
	return withdraw
wd = make_withdraw(20)
wd(5)
wd(3)
>>>15
>>>12
  • The Cost of Non-Local Assignment
  • Implementing Lists and Dictionaries

In Python , using reserved(str/list/tuple/range) can just return a iterator , so if you want to use it ,you have to modify it into other type such as list .

  • Dispatch Dictionaries

I don't recommend using this


Actually I do not what this means.

By storing the balance in the dispatch dictionary rather than in the account frame directly, we avoid the need for nonlocal statements in deposit and withdraw.
  • Propagating Constraints

This is really interesting , while you learning other coding language ,have you ever thought of the one-direction computation of it?Generally we use parameters to calculate the others by one certain function. What if you only have the others? Define another function? That's troublesome.

from operator import mul, truediv
from operator import add, sub


def make_ternary_constraint(a, b, c, ab, ca, cb):
    """The constraint that ab(a,b)=c and ca(c,a)=b and cb(c,b) = a."""

    def new_value():
        av, bv, cv = [connector['has_val']() for connector in (a, b, c)]
        if av and bv:
            c['set_val'](constraint, ab(a['val'], b['val']))
        elif av and cv:
            b['set_val'](constraint, ca(c['val'], a['val']))
        elif bv and cv:
            a['set_val'](constraint, cb(c['val'], b['val']))

    def forget_value():
        for connector in (a, b, c):
            connector['forget'](constraint)

    constraint = {'new_val': new_value, 'forget': forget_value}
    for connector in (a, b, c):
        connector['connect'](constraint)
    return constraint


def adder(a, b, c):
    """The constraint that a + b = c."""
    return make_ternary_constraint(a, b, c, add, sub, sub)


def multiplier(a, b, c):
    """The constraint that a * b = c."""
    return make_ternary_constraint(a, b, c, mul, truediv, truediv)


def converter(c, f):
    """Connect c to f with constraints to convert from Celsius to Fahrenheit."""
    u, v, w, x, y = [connector() for _ in range(5)]
    multiplier(c, w, u)
    multiplier(v, x, u)
    adder(v, y, f)
    constant(w, 9)
    constant(x, 5)
    constant(y, 32)


def constant(connector, value):
    """The constraint that connector = value."""
    constraint = {}
    connector['set_val'](constraint, value)
    return constraint


def connector(name=None):
    """A connector between constraints."""
    informant = None
    constraints = []

    def set_value(source, value):
        nonlocal informant
        val = connector['val']
        if val is None:
            informant, connector['val'] = source, value
            if name is not None:
                print(name, '=', value)
            inform_all_except(source, 'new_val', constraints)
        else:
            if val != value:
                print('Contradiction detected:', val, 'vs', value)

    def forget_value(source):
        nonlocal informant
        if informant == source:
            informant, connector['val'] = None, None
            if name is not None:
                print(name, 'is forgotten')
            inform_all_except(source, 'forget', constraints)

    connector = {'val': None,
                 'set_val': set_value,
                 'forget': forget_value,
                 'has_val': lambda: connector['val'] is not None,
                 'connect': lambda source: constraints.append(source)}
    return connector


def inform_all_except(source, message, constraints):
    """Inform all constraints of the message, except source."""
    for c in constraints:
        if c != source:
            c[message]()


celsius = connector('Celsius')
fahrenheit = connector('Fahrenheit')
converter(celsius, fahrenheit)
celsius['set_val']('user', 25)
>>>
Celsius = 25
Fahrenheit = 77.0

Home Work 3

Just take care of the structure

16. Mutable Functions

Lab 6

The way I finish lab6 is too complex,maybe there is something that I had missed .Such as:

def make_fib():
    pre_num=1
    pre_pre_num=0
    count=0
    def fib_in():
        nonlocal count
        nonlocal pre_num
        nonlocal pre_pre_num
        if count==0:
            count=count+1
            return pre_pre_num
        elif count==1:
            count=count+1
            return pre_num
        else:
            result=pre_num+pre_pre_num
            pre_pre_num=pre_num
            pre_num=result
            return result
    return lambda :fib_in()

On the internet,i find this:

def make_fib():
    curr, nex = 0, 1
    def helper():
        nonlocal curr, nex
        curr, nex = nex, curr + nex
        return nex - curr
    return helper
————————————————
Link:https://blog.csdn.net/Denny5608/article/details/120625505

17. Iterators

18. Objects

Text :Ch2.5

  • Objects and Classes
  • Defining Classes

__init__ (two underscores on each side of the word "init"), and is called the constructor for the class.


This part of content is fundamental.

  • Message Passing and Dot Expressions

Ok,strange knowledge has increased

We can see the difference in the interactive interpreter by calling `type` on the returned values of dot expressions. As an attribute of a class, a method is just a function, but as an attribute of an instance, it is a bound method:
>>> type(Account.deposit)
<class 'function'>
>>> type(spock_account.deposit)
<class 'method'>

Naming Conventions. Class names are conventionally written using the CapWords convention (also called CamelCase because the capital letters in the middle of a name look like humps). Method names follow the standard convention of naming functions using lowercased words separated by underscores.


If we assign to the named attribute interest of an account instance, we create a new instance attribute that has the same name as the existing class attribute.

class Account:
        interest = 0.02            # A class attribute
        def __init__(self, account_holder):
            self.balance = 0
            self.holder = account_holder
        # Additional methods would be defined here
>>> spock_account = Account('Spock')
>>> kirk_account = Account('Kirk')
>>> spock_account.interest
0.02
>>> kirk_account.interest
0.02
>>> Account.interest = 0.04
>>> spock_account.interest
0.04
>>> kirk_account.interest
0.04
>>> Account.interest = 0.04
>>> spock_account.interest
0.04
>>> kirk_account.interest
0.04
>>> kirk_account.interest = 0.08
>>> kirk_account.interest
0.08
>>> spock_account.interest
0.04
# Changes to the class attribute interest will affect spock_account, but the instance attribute for kirk_account will be unaffected.
  • Class Attributes
  • Inheritance
  • Using Inheritance
  • Multiple Inheritance
class CheckingAccount(Account):
        """A bank account that charges for withdrawals."""
        withdraw_charge = 1
        interest = 0.01
        def withdraw(self, amount):
            return Account.withdraw(self, amount + self.withdraw_charge)
class SavingsAccount(Account):
        deposit_charge = 2
        def deposit(self, amount):
            return Account.deposit(self, amount - self.deposit_charge)
class AsSeenOnTVAccount(CheckingAccount, SavingsAccount):
        def __init__(self, account_holder):
            self.holder = account_holder
            self.balance = 1           # A free dollar!

>>> such_a_deal = AsSeenOnTVAccount("John")
>>> such_a_deal.balance
1
>>> such_a_deal.deposit(20)            # $2 fee from SavingsAccount.deposit
19
  • The Role of Objects

Abstraction barriers enforce the boundaries between different aspects of a large program.

Object-oriented programming is particularly well-suited to programs that model systems that have separate but interacting parts.

Home Work 4

Before doing this ,we should know how to generate a type 'generator' output.


About yield

yield详解 - 知乎 (zhihu.com)


Extra Problems are not considered for now

19. Inheritance

Lab 7

Note:I don't know why there is not the class of MosterTruck,it will be used during unlocking:

class MonsterTruck(Car):
    size = 'Monster'

    def rev(self):
        print('Vroom! This Monster Truck is huge!')

    def drive(self):
        self.rev()
        return Car.drive(self)

Project Ants

20. Representation

Text Ch2.7

  • String Conversion

The difference between strandrepr

>>> print(str('123'))       
123                         
>>> print(str(123))         
123                         
>>> print(repr('123'))      
'123'                       
>>> print(repr(123))        
123                         

""" The repr function always invokes a method called repr on its argument.""" stris the same as repr

>>>from datetime import date
>>>tues = date(2011, 9, 12)
>>>repr(tues)
'datetime.date(2011, 9, 12)'
>>>tues.__repr__()
'datetime.date(2011, 9, 12)'
  • Special Methods

Generally,we think we are using some external methods when we call len(),but actually we just invoke some internal methods


Python uses a sequence's length to determine its truth value, if it does not provide a __bool__ method. Empty sequences are false, while non-empty sequences are true.


The __getitem__ method is invoked by the element selection operator, but it can also be invoked directly.

>>> 'Go Bears!'[3]
'B'
>>> 'Go Bears!'.__getitem__(3)
'B'
  • Multiple Representations
  • Generic Functions

21. Composition

Text :Ch2.9

Home Work 5

This home work need some precondition of data structure,there I recommend a tutorial website for you:(you can choose the language if you like)

visualising data structures and algorithms through animation - VisuAlgo

22. Efficiency

Text Ch2.8

Lab 8

  • reverse_other

Not my code.

ef reverse_other(t):
    """Mutates the tree such that nodes on every other (odd-depth) level
    have the labels of their branches all reversed.

    >>> t = Tree(1, [Tree(2), Tree(3), Tree(4)])
    >>> reverse_other(t)
    >>> t
    Tree(1, [Tree(4), Tree(3), Tree(2)])
    >>> t = Tree(1, [Tree(2, [Tree(3, [Tree(4), Tree(5)]), Tree(6, [Tree(7)])]), Tree(8)])
    >>> reverse_other(t)
    >>> t
    Tree(1, [Tree(8, [Tree(3, [Tree(5), Tree(4)]), Tree(6, [Tree(7)])]), Tree(2)])
    """
    "*** YOUR CODE HERE ***"

    def reverse(t, flag):
        if t.is_leaf():
            return
        if flag:
            n = len(t.branches)
            for i in range(n // 2):
                t.branches[i].label, t.branches[n - i - 1].label = t.branches[n - i - 1].label, t.branches[i].label
        for b in t.branches:
            reverse(b, 1 - flag)

    reverse(t, 1)

23. Decomposition

24. Scheme

Text Ch3.1-2

  • Expressions
  • Definitions
  • Compound values
  • Symbolic Data

This part is mainly focus on the syntax of Scheme . if you have enough fundamental knowledge of CS , you can quickly get the idea of it.

Lab 10

Note: You have to start with the file named lab10.scm


The Problem define lstreqire making the same structure as the pic shows

Home Work 6

It seems like I need to use square ,but I don't. bc of lazy.

(define (square x) (* x x))


(define (pow x y)
  (cond ((= 1 x) 1) ((= 0 y) 1) (else (* x (pow x (- y 1)))))
)

25. Exceptions

Text Ch.3.3

26. Calculator

Text Ch.3.4

Home Work 7

If you have no thought ,you can just think about how it works in python . Then interpreter it into scm . Note: Use existing function .

27. Interpreters

Lab 11

Home Work 8

posted @ 2022-11-24 16:40  海之龙  阅读(673)  评论(0)    收藏  举报