# CS61A学习笔记 week1

~~ 绝赞更新中！~~ 开学了，下期休刊！

\\ 整除
** exp

## assignment statement

a = b
a1,a2 = b1,b2


python的函数是可以通过赋值重定义的，如：

max = min


## User-Defined Functions

def <name>(<formal parameters>):
return <return expression>


def square(x):
return mul(x , x)
def sum_squares(x, y):
return square(x) + square(y)


## None

python中的无返回值（默认返回值），type是NoneType

print(print(1), print(2))

output:
1
2
None None


## Conditional statements

if x < 0:
return -x
elif x == 0:
return x
else:
return x


## Boolean

### Boolean operators

and中，如果所有值都为True，返回最后一个值

or中，如果所有值都为False，也返回最后一个值

## Iteration

while <expression>:
<suite>
for <variable> in <interable>:
<suite>


## assert

assert <expression>,<message>


## 作业

hw01,hw02,lab00,lab01

project1(hog)

# CS61A学习笔记 week2

## Self-Reference

def print_all(x):
print(x)
return print_all

print_all(1)(3)(5)


## Decorators

def trace(fn):
def traced(*args):
print('Calling',fn,'on argument',*args)
return fn(*args)
return traced

@trace
def triple(x):
return 3*x


hw03,lab02,lab03

# CS61A学习笔记 week3

## lists

>>> odds = [41,53,47,49]
>>> odds[1]
43


### len

>>> len(odds)
4


### append

>>> s = [2,3]
>>> t = [5,6]
>>> s.append(t)
>>> s
[2, 3, [5, 6]]


### extend

>>> s = [2,3]
>>> s.extend(t)
>>> s
[2, 3, 5, 6]


### +

>>> s = [2,3]
>>> a = s + t
>>> a
[2, 3, 5, 6]


### slice assignment

$$s[a:b] = t$$

$$a\ b$$ 默认值为序列左右两端

>>> b = a[1:]
>>> b
[3, 5, 6]
>>> s = [2,3]
>>> t = [5,6]
>>> s[0:0] = t
>>> s
[5, 6, 2, 3]
>>> s[3:] = t
>>> s
[5, 6, 2, 5, 6]
>>> s[2:] = t
>>> s
[5, 6, 5, 6]


### pop

>>> s = [2,3]
>>> s.pop()
3
>>> s
[2]
>>> s.pop()
2
>>> s
[]
>>> s.pop()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: pop from empty list


### remove

>>> t = [5,6,5,6]
>>> t.remove(6)
>>> t
[5, 5, 6]


## containers

>>> 41 in odds
True


## For Statements and Ranges

for <name> in <expression>:
<suite>


range:连续整数，左闭右开，左端参数默认是0，iterable

## list comprehension

>>> odds = [1,3,5,7,9]
>>> [x+1 for x in odds]
[2,4,6,8,10]
>>> [x+1 for x in odds if 25 % x ==0]
[2,6]


## strings

string也可以当作字符数组访问，下标从0开始

string的list比较特殊，in操作符可以判断substring

## Dictionary

numerals = {'I': 1, 'V': 5, 'X': 10}
>>> numerals.keys()
dict_keys(['I', 'V', 'X'])
>>> numerals.values()
dict_values([1, 5, 10])
>>> numerals.items()
dict_items([('I', 1), ('V', 5), ('X', 10)])
>>> items = [('I', 1), ('V', 5), ('X', 10)]
>>> dict(items)
{'I': 1, 'V': 5, 'X': 10}
>>> 'X' in numerals
True
>>> numerals.get('X')
10
>>> numerals.get('X-ray')
>>> numerals.get('X-ray',0) # 默认值
0
# dictionary comprehension
>>> squares = {x:x*x for x in range(10)}
>>> squares[7]
49
>>> {[1]:2}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'


## Raising Exceptions

raise <expression>
raise TypeError('111!')
#还有NameError,KeyError,RuntimeError


## Try Statements

try:
<try suite>
except <exception class> as <name>:
<except suite>
...


## Reduce

from functools import reduce
reduce(<function>,<list>,<initial_element>)
reduce(mul,[1,2,3],1)


## Processing Container Values

>>> max(range(10),key = lambda x: 7-(x-4)*(x-2))
3
# 即keyfunc(x)最大的x


## Object

ord(s) #ascii
s.upper()
s.lower()
s.swapcase()


## Mutation Operations

list 和 dictionary 是 mutable type，可以mutation

## Identity & Equality

a is b # identity,是否bound到相同的元素
a == b # Equality,值是否相同


lab04,lab05,hw04

project2(cat)

# CS61A学习笔记 week4

## nonlocal

nonlocal <name>


python 是把声明变量和变量赋值都放在 assignment 写法里的，注意二者的区别

## Iterator

iter(iterable) : return an iterator
next(iterator) : return the next element in an iterator


dictionary有不同的iterators:

k = iter(d.keys())
v = iter(d.values())
i = iter(d.items())


### For Statements

for一个iterator的时候，会枚举当前元素以及之后的所有元素

## Built-in Iterator Functions

reversed,list,tuple,sorted: 顾名思义，把iterator变成各种形式

next(incr, v) 当StopIteration时返回v

## generator

### yeild from statement

for x in a:
yield x


yeild from a


lab06,lab07,hw05

midterm

# CS61A学习笔记 week5

## Class Statements

class <name>:
<suite>


>>> class Account:
def __init__(self, account_holder):
self.balance = 0
self.holder = account_holder


## Method

def deposit(self, amount):
self.balance += amount
return self.balance


## Attributes

built-in functions:

>>> getattr(john, 'balance') # = john.balance
>>> hasattr(john, 'balance') # check attrribute
True


Class里的Attributes可以是function，也可以是简单的值。

## Methods and Functions

Object + Function = Bound method, 即把Object传入一个Class里的Function的self参数就得到了method

>>> Account.deposit(tom_account,1001) # <class 'function'>
1011
>>> tom_account.deposit(1000) # <class 'method'>
2011


## Class Attributes

class Account:
interest = 0.02
def __init__(self, account_holder):
self.balance = 0
self.holder = account_holder
...
...
>>> tom_account.interest
0.02
>>> jim_account.interest
0.02


instance attribute：self.name（在init里声明或者在外面assign）

class的这种变量也可以被self拿来用(self.interest)

## Attribute Assignment

1. 计算左侧表达式，得到object
2. 如果左侧实例（instance）有一个这样的attribute，返回值
3. 否则在对应的class里去找，返回值
4. 如果找到的是一个函数，则返回bound method

## Inheritance

class <name>(<base class>):
<suite>


super(): 另一种访问上一级class (base class) 的方式

## Multiple Inheritance

attribute名称冲突时优先选在继承树上近的那个

John老师认为不好用（救世啊！）

isinstance：判断是否为class的实例

@property：把method转化为attribute，不加括号可以直接调用

@<attribute>.setter： 用于已经@property的method，可以进行赋值等操作

## Memoization

python的一种记忆化写法：使用dictionary和decorator：

def memo(f):
cache = {}
def memoized(n):
if n not in cache:
cache[n] = f(n)
return cache[n]
return memoized


## String Representations

class里的关键字__str____repr__

__repr__ 返回一个python表达式（string），其运行的结果是object本身(eval(repr(object)) == object)

__str__ 返回一个更容易被人类理解的表达式，print出来的就是__str__

## Implementing repr and str

instance attribute called __repr__ or __str__ is ignored!

Only class attributes are found

def repr(x):
return type(x).__repr__(x)


## Special Method Names

__add__ : 调用+，左结合

__radd__ : +右结合

__bool__  __float__ : 强制转换

## Sets

python的内置set

>>> s = {'one','two','three','four','four'}
>>> 'three' in s
True
>>> len(s)
4
>>> s.union({'one','five'}) # 并
{'three','five','one','four','two'}
>>> s.intersection({'six','five','four','three'})# 交
{'three','four'}
>>> s
{'three','one','four','two'} #union和intersection不改变s
>>> s.update(<tuple,list,dict>)
>>> s.clear()


## *args and **kwargs

*args: 剩下的无名参数（args是一个tuple）

*kwargs: 剩下的关键字参数（kwargs是一个dictionary）

>>> def pr(*args,**kwargs):
print('args=',args)
print('kwargs=',kwargs)
>>> pr(1,2,3,a=2,b=4,c=6)
args= (1,2,3)
kwargs= {'a':2,'b':4,'c':6}


## 作业

lab08,lab09,hw06

project3(Ants)(big big project!)

# CS61A学习笔记 week6

## scheme

> (Integer? 1)
#t
> (+ 1 2)
3


## Special Forms

• If expression: (if <predicate> <consequent> <alternative>)
• And and or: (and <e1>...<en>),or(<e1>...<en>)
• Binding symbols: define <symbol> <expression>
• New procedures: define (<symbol> <formal parameters>) <body>

## Lambda Expressions

(lambda (<formal-parameters>) <body>)


## Lists

cons: constructor

car: 返回第一个元素

cdr: 返回剩下的元素

nil: empty list

> (cons 1 (cons 2 nil))
(1 2)


## Symbolic Programming

> 'a
a
> (quote a)
a
> (list 1 'a)
(1 a)
> (list 1 a)
Error


## Macros

macro：自定义special form，使用define-macro定义的函数不会先eval，相当于把参数先quote起来

## 作业

lab10(刚好10个question)

lab11

hw07

project4(scheme)

posted @ 2023-01-03 02:33  lcyfrog  阅读(564)  评论(0编辑  收藏  举报