开始神课CS61A!
跟的是FALL 2020,原先一直以为OK没法用,但在做hog时发现不用Berkeley的账号也可以保存更新!里面的一些前置问题也能出来,只不过没发评分而已,做project的时候这些前置问题有很大的帮助,大家可以去试试!
link: https://inst.eecs.berkeley.edu/~cs61a/fa20/
作业全部代码会逐渐更新在github,现第一单元的已经全部更完啦
(指路:https://github.com/Louuucas99/CS61A)
这里并不会整理整个知识框架,只是总结一些没见过的简单用法和一些需要常回顾或者还是不太理解的代码。
1.Assertion
是检错的一种代码。在正常的语句前面加,后面是对的就正常运行,错的话会终止运行报错
(cons:只能一行一行检验不能大量检查)
eg.
>>>assert 3>2 ,'Math is broken' #对的无反应
>>>assert 2>3 ,'Math is broken' #错的报错
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError: Math is broken
2.Doctests
检错代码。简单解释就是,在代码的注释里(文本行里)写可以测试的代码,用doctest就真的会把你注释里的例子运行出来看实际上对不对
(你以为你写在注释里的没用,但实际上只要箭头格式对了还真的有用)
eg.用 python -m doctest -v xx.py 进行检错
3.补常识
①在cmd里直接运行python文件,在前面加 -i
② 可以生成visualized流程图的网站!!!
(在higher order functions里搞不懂怎么嵌套的时候常用):
http://pythontutor.com/composingprograms.html#mode=display
运行界面举例如下:
- DISC02 1.1
虽然return可直接返回数据,但也只能返回一个就结束了
def keep_ints(cond, n):
"""
Print out all integers 1..i..n where cond(i) is true
>>> def is_even(x):
... # Even numbers have remainder 0 when divided by 2.
... return x % 2 == 0
>>> keep_ints(is_even, 5)
2
4
"""
i = 1
while i <= n:
if cond(i):
print(i)
i += 1
自己当时的bug,将print(i)写成return i,调用keep_ints(is_even, 5)时只输出一个2就没了
- 两种方法迭代解
def remove(n, digit):
"""Return all digits of N that are not DIGIT, for DIGIT less than 10.
>>> remove(231, 3)
21
>>> remove(240132, 2)
4013
"""
#法一
kept, digits = 0, 0
while n != 0:
n, last = n // 10, n % 10
if last != digit:
kept = kept / 10 + last
digits = digits + 1
return round(kept * 10 ** (digits - 1))
#法二
kept, digits = 0, 0
while n != 0:
n, last = n // 10, n % 10
if last != digit:
kept = kept + last * 10 ** digits
digits = digits + 1
return kept
- Iteration & Recursion
eg.
RETURSION
def hailstone(x):
"""Print the hailstone sequence starting at x and return its
length.
>>> a = hailstone(10)
10
5
16
8
4
2
1
>>> a
7
"""
length = 1
while x != 1:
print(x)
if x % 2 == 0:
x = x // 2
else:
x = 3 * x + 1
length = length + 1
print(x)
return length
IETERATION
def hailstone(x):
if n == 1:
return 1
elif n % 2 == 0:
return 1+hailstone(n//2)
else:
return 1+hailstone(n * 3 + 1)