查看: 7543| 回复: 25
跳转到指定楼层
上一主题 下一主题
收起左侧

跟课 CS61A- Fall 2015

全局:
公开课
学校名称: UC Berkeley
Unit号: 16
开课时间: 2015-08-26
课程全名: CS61A--The Structure and Interpretation of Computer Programs
平台: 其他

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
本帖最后由 lh6210 于 2015-10-9 13:35 编辑

这个问题困扰了我好几天,写出来主要给像我一样基础薄弱的同学们,好让开头顺利些: 如何像老师一样右边写文件, 左边调试该文件?
右边是 text editor, 左边是 os command line editor。
如果你和我一样是 windows os,则打开 cmd 命令行,进入你后面放置程序文件的文件夹,我这里选择是 c:\python3.5文件夹,即python3.5安装路径下(c:\xxx,  d:\xxx\xxx皆可)。
C:\Users\user>cd c:\python3.5
c:\python3.5>
打开 atom, ctrl + n 新建文件,然后 ctrl +s 保存文件,保存路径为 你上面命令行进入的路径,于是我就保存在 c:\python3.5 文件夹中。
这样就可以右边文件做修改,然后马上左边做  python -i filename了。




上一篇:OOP in Java - week 3 - 交作业
下一篇:OOP in Java (UCSD) -- week 4 交作业
推荐
 楼主| lh6210 2015-11-16 11:50:20 | 只看该作者
全局:
if19870314 发表于 2015-11-16 11:38
还有python ok -q xxx
也在课里貌似没看到过

课程里面都有的,它的知识点可能会有的在视频里,有的在reading里,python ok的使用是在 lab0 还是 lab1中有介绍的。
ok 是一个检查作业和交作业的功能,因为我们不是 uc berkeley的学生,不能提交作业,所以这个是辅助作用。
平时可以用 python -i, 可能在 lab0或者 lab1中有介绍到。
加油吧~
回复

使用道具 举报

推荐
 楼主| lh6210 2015-11-3 19:12:37 | 只看该作者
全局:
本帖最后由 lh6210 于 2015-11-3 19:37 编辑

lab02: Higher order functions and lambdas

Question 1:
t = lambda f: lambda x:f(f(f(x)))
s = lambda x: x+1
求: t(s)(0)
解:
t(s)= lambda x: s(s(s(x)))
t(s)(0) = s(s(s(0))) =3

bar = lambda y: lambda x: pow(x,y)
求bar()(15)
解: missing one argument

foo = lambda :32
foobar= lambda x,y:x//y
a= lambda x: foobar(foo(), bar(4)(x))
求a(2)
解:a(2)= foobar( foo(), bar(4)(2))
    = foobar(32, pow(4,2))
    = foobar (32, 16)
    = 32//16=2

b = lambda x,y: print('summer')
c=b(4,'dog')
求print(c)
解:
c = None, 显示为 summer
print(c) 即 print(None) = None

Question 2:
a = lambda x: x*2 +1
def b(b,x):
    return b(x + a(x))
x=3
求 b(a, x)
解:
b(a, x) will return a(x + a(x)) = a(3 + a(3)) =21

Question 3:
def first(x):
    x +=8
    def second(y):
        print('second')
        return x+y
    print('first')
    return second
求 f= first(15)
解:
print('first')    显示  first
求f
解:
function <second> ...
求f(16)
解:
second
39

def even(f):
    def odd(x):
        if x<0:
            return f(-x)
        return f(x)
    return odd

stevphen = lambda x:x
stewart = even(stevphen)
求 stewart, stewart(61),  stewart(-4)
解:
stewart: function <odd> ...
stewart(61):  61
stewart(-4) : 4

Question 4:
Define a function make_derivative that returns a function: the derivative of a function f.
def make_derivative(f, h=1e-5):
    ....
    return g
assuming that f is a single-variable mathematical function, its derivative will also be a single-variable function. When called with a number a, the derivative will estimate the slope of f at point (a, f(a)).
g(a) = (f(a+h) - f(a))/a (h = 1e-5)
解:
def make_derivative(f, h=1e-5):
    def g(a):
        return (f(a+h) - f(a))/h
    return g

Question 5:
from operator import add , sub
def caesar_generator(num, op):
    def f(x):
        return num_to_letter(op(letter_to_num(x), num))
    return f

等同于  return lambda x: num_to_letter(op(letter_to_num(x), num)

Question 6:
def make_encrypter(f1, f2, f3):
    f1, f2, f3 = looper(f1), looper(f2), looper(f3)
    return lambda x: f1(f2(f3(x)))

def make_decrypter(f1, f2, f3):
    f1, f2, f3 = looper(f1), looper(f2), looper(f3)
    return lambda x: f3(f2(f1(x)))

Question 7:
def generator():
    ...
    return make_encrypter(f1, f2, f3), make_decrypter(f1, f2, f3)

Question 8:
>>> def troy():...     abed = 0...     while abed < 3:...         britta = lambda: abed...         print(abed)...         abed += 2...     annie = abed...     annie += 1...     abed = 6 # seasons and a movie...     return britta>>> jeff = troy()
troy()的返回值是  britta, britta = lambda: abed [parent: frame1]。 在 frame1 中,abed最后被更新到6, 所以可以理解为 britta() = 6

Question 9
>>> def go(bears):...     gob = 3...     print(gob)...     return lambda ears: bears(gob)>>> gob = 4>>> bears = go(lambda ears: gob)______
>>> bears(gob)______
解:
改写下  go 函数:
def go(bears):
    gob =3
    print(gob)
    def h(ears):
        return bears(gob)
    return h


根据function go的定义, 如果f是一个single argument函数
go(f) return  h, h(ears) will return f(3)  (frame1中 gob=3)
Global frame中, gob=4
f1 = lambda ears: gob = lambda ears: 4
f1(3) =4
bears = go(lambda ears: gob) = go(f1)
bears(gob) = bears(4) = go(f1)(4) = f1(3)
f1(3) =4 于是 得出结果为4

Question 10:
  1. def count_cond(condition):
  2.     def f(n):
  3.         count, i=0,1
  4.         while i<=n:
  5.             if condition(n, i):
  6.                 count +=1
  7.             i+=1
  8.         return count
  9.     return f

  10. cond_factors = lambda n, i: n%i ==0
  11. count_factors = count_cond(cond_factors)

  12. is_prime= lambda n,i : count_factors(i)==2
  13. count_primes = count_cond(is_prime)
复制代码
Question 11
这道题与 solution 略有不同:
  1. def cycle(f1, f2, f3):
  2.     def g(n):
  3.         def h(x):
  4.             if n==0:
  5.                 return x
  6.             else:
  7.                 i =1
  8.                 while i<=n:
  9.                     if i%3 ==1:
  10.                         x = f1(x)
  11.                     elif i%3 ==2:
  12.                         x = f2(x)
  13.                     else:
  14.                         x = f3(x)
  15.                     i +=1
  16.                 return x
  17.         return h
  18.     return g

  19. add1 = lambda x: x+1
  20. times2 = lambda x: x*2
  21. add3 = lambda x: x+3

  22. my_cycle = cycle(add1, times2, add3)
  23. identity = my_cycle(0)
  24. add1_then_double = my_cycle(2)
  25. do_all_functions = my_cycle(3)
复制代码
回复

使用道具 举报

推荐
 楼主| lh6210 2015-10-15 11:32:29 | 只看该作者
全局:
本帖最后由 lh6210 于 2015-10-15 11:38 编辑

1.6 章节开始感觉难度提升了~  总结一下可能会帮助理解:
1.6.2   
一切从万用的 improve(update, close, guess=1) 开始,这个是 1.6反复用到的 general function:
def improve(update, close, guess=1):
    while not close(guess):
        guess = update(guess)
    return guess
在此基础上,例子为  golden ratio的计算。  反复计算  1/x +1(golden_update), 结束条件为  x*x- (x+1)=0
def golden_update(x):
    return 1/x +1

def golden_close(x):
    return approx_eq(x*x , x+1)

def approx_eq(a,b , tolerance=1e-10):
    return abs(a-b) < tolerance

于是得出 function:
def golden_compute():
    return improve(golden_update, golden_close)

1.6.3  Nested Definitions
举例为  square root 的计算。 反复计算  (x + a/x)/2(root_update), 结束条件为   x*x -a =0
这里 1.6.3 与 1.6.2 相比较, 在 反复计算与结束条件的公式中,多了一个变量 a, 所谓的 nested definition,于是 相关的定义需要放在 parent definition中。
def improve(update, close, guess=1):
    while not close(guess):
        guess = update(guess)
    return guess

def square_root(a):
    def root_update(x):
        return  (x+a/x)/2
    def root_close(x):
        return approx_eq(x*x, a)
    return improve(root_update, root_close)

def approx_eq(a, b, tolerance=1e-10):
    return abs(a-b) < tolerance

1.6.4, 1.6.5  Functions as returned value
提到了 著名的  Newton's Method
Newton's method is a classic iterative approach to finding the arguments of a mathematical function that yields a return value of 0.
def newton_update(f, df):
    def update(x):
        return x - f(x)/df(x)
    return update
利用这个 newton_update function可以定义一个通用的 function来计算任何  pow(x,n) -a:
def find_zero(f, df):
    def near_zero(x):
        return approx_eq(f(x), 0)
    return improve(newton_update(f,df), near_zero)
有了这个通用的 function, 我们可以拿来定义任何的  pow(x,n)-a 的求解,比如 求square_root:
-------------------------------------------------------------------------------------------
def improve(update, close, guess=1):
    while not close(guess):
        guess = update(guess)
    return guess

def approx_eq(a, b, tolerance=1e-10):
    return abs(a-b) < tolerance

def newton_update(f, df):
    def update(x):
        return x - f(x)/df(x)
    return update

def find_zero(f, df):
    def near_zero(x):
        return approx_eq(f(x), 0)
    return improve( newton_update(f,df), near_zero)

---------------------------------------------------------------------------------------------------   这部分拿来即可,简称 标蓝部分
余下的工作是定义 f(x)与 df(x):
def square_root_newton(a):
    def f(x):
        return x*x -a
    def df(x):
        return 2*x
    return find_zero(f, df)

同理,定义  cube_root_newton(a):
-----------------------------------------------
.......
-----------------------------------------------  标蓝部分

def cube_root_newton(a):
    def f(x):
        return x*x*x -a
    def df(x):
        return 3*x*x
    def near_zero(x):
        return approx_eq(f(x), 0)
    return find_zero(f, df)

在此基础上,老师继续归纳总结:generalizing to roots of arbitrary degree n, we compute f(x)=pow(x,n)-a, and it's derivative df(x)=n*pow(x,n-1)
-----------------------------------------------
.......
-----------------------------------------------  标蓝部分

def power(x, n):
    product, k = 1, 0
    while k <n:
        product, k = product * x, k+1
    return product

def nth_root_newton(a, n):
    def f(x):
        return power(x,n) -a
    def df(x):
        return n* power(x, n-1)
    def near_zero(x):
        return approx_eq(f(x), 0)
    return find_zero(f, df)
回复

使用道具 举报

🔗
 楼主| lh6210 2015-10-9 13:12:04 | 只看该作者
全局:
1.6.2   视频中出现了   lambda function。  这个是什么鬼?
在做了 检索后,大概明白过来, 把介绍粘贴在下面:

功能性质:The lambda operator or lambda function is a way to create small anonymous functions, i.e. functions without a name. These functions are throw-away functions, i.e. they are just needed where they have been created.
高级用法:Lambda functions are mainly used in combination with the functions filter(), map() and reduce().
历史渊源:The lambda feature was added to Python due to the demand from Lisp programmers.
The general syntax of a lambda function:
lambda argument_list: expression
e.g.1:
>>> f = lambda x, y : x + y
>>> f(1,1)
2
e.g.2:
>>> lambda x: x**2
<function <lambda> at 0x00547270>
>>> (lambda x: x**2) (8)
64
>>> g = lambda x: x**2
>>> g(8)
64
回复

使用道具 举报

🔗
nelson16 2015-10-22 13:22:19 | 只看该作者
全局:
你最好跟2013年的... 这两年我们学校autograder不对外开放了貌似
回复

使用道具 举报

🔗
 楼主| lh6210 2015-10-27 15:53:20 | 只看该作者
全局:
nelson16 发表于 2015-10-22 13:22
你最好跟2013年的... 这两年我们学校autograder不对外开放了貌似

看了 fall 2013, 发现solution没有,觉得 2015还是可以跟的,至少可以有答案参考。

不过谢谢建议了
回复

使用道具 举报

🔗
 楼主| lh6210 2015-10-27 16:17:35 | 只看该作者
全局:
quiz01
  1. def diff(x, y, z):
  2.     """Return whether one argument is the difference between the other two.

  3.     x, y, and z are all integers.

  4.     >>> diff(5, 3, 2) # 5 - 3 is 2
  5.     True
  6.     >>> diff(2, 3, 5) # 5 - 3 is 2
  7.     True
  8.     >>> diff(2, 5, 3) # 5 - 3 is 2
  9.     True
  10.     >>> diff(-2, 3, 5) # 3 - 5 is -2
  11.     True
  12.     >>> diff(-5, -3, -2) # -5 - -2 is -3
  13.     True
  14.     >>> diff(-2, 3, -5) # -2 - 3 is -5
  15.     True
  16.     >>> diff(2, 3, -5)
  17.     False
  18.     >>> diff(10, 6, 4)
  19.     True
  20.     >>> diff(10, 6, 3)
  21.     False


  22.     """
复制代码
def diff(a,b,c):
    if a+b ==c:
        return True
    elif a+c==b:
        return True
    elif b+c==a:
        return True
    else:
        return False

还有一种表达方式:
def diff(a,b,c):
    return a+b==c or a+c==b or b+c==a
  1. def abundant(n):
  2.     """Print all ways of forming positive integer n by multiplying two positive
  3.     integers together, ordered by the first term. Then, return whether the sum
  4.     of the proper divisors of n is greater than n.

  5.     A proper divisor of n evenly divides n but is less than n.

  6.     >>> abundant(12) # 1 + 2 + 3 + 4 + 6 is 16, which is larger than 12
  7.     1 * 12
  8.     2 * 6
  9.     3 * 4
  10.     True
  11.     >>> abundant(14) # 1 + 2 + 7 is 10, which is not larger than 14
  12.     1 * 14
  13.     2 * 7
  14.     False
  15.     >>> abundant(16)
  16.     1 * 16
  17.     2 * 8
  18.     4 * 4
  19.     False
  20.     >>> abundant(20)
  21.     1 * 20
  22.     2 * 10
  23.     4 * 5
  24.     True
  25.     >>> abundant(22)
  26.     1 * 22
  27.     2 * 11
  28.     False
  29.     >>> r = abundant(24)
  30.     1 * 24
  31.     2 * 12
  32.     3 * 8
  33.     4 * 6
  34.     >>> r
  35.     True


  36.     """
复制代码
这道题, abundant(16)要注意,4*4=16,这里4只加了一次。
def abundant(n):
    total, i = 0,1
    while i*i <=n:
        if n%i ==0:
            print(i, '*', n//i)
            total = total + i
            if n//i !=i and n//i <n:
                total = total + n//i
        i = i+1
    return total > n

solution里面,标黄语句是另外的表述:
if i>1 and i*i <n

这句语句是要排除   1*n =n 中的 n 与 i*i =n中 i, solution 的表达方式更加 简洁一些。
  1. def amicable(n):
  2.     """Return the smallest amicable number greater than positive integer n.

  3.     Every amicable number x has a buddy y different from x, such that
  4.     the sum of the proper divisors of x equals y, and
  5.     the sum of the proper divisors of y equals x.

  6.     For example, 220 and 284 are both amicable because
  7.     1 + 2 + 4 + 5 + 10 + 11 + 20 + 22 + 44 + 55 + 110 is 284, and
  8.     1 + 2 + 4 + 71 + 142 is 220

  9.     >>> amicable(5)
  10.     220
  11.     >>> amicable(220)
  12.     284
  13.     >>> amicable(284)
  14.     1184
  15.     >>> r = amicable(5000)
  16.     >>> r
  17.     5020


  18.     """
复制代码
def sum_divisors(n):
    total , d = 0, 1
    while d<n:
        if n%d ==0:
            total = total + d
        d = d+1
    return total

def amicable(n):
    n= n+1
    while True:
        m = sum_divisors(n)
        if m !=n and sum_divisors(m)==n:
            return n
        n = n+1





回复

使用道具 举报

🔗
 楼主| lh6210 2015-10-28 12:34:40 | 只看该作者
全局:
lab01.py
实验过程中的几个概念:
boolean operators:  and , or , not
这三者的关系如下:
not :  has the highest priority
and:  normal
or:  has the lowest priority
所以:  not 5 or 3==4 and 2>3  等同于  (not 5) or (3==4 and 2>3)
而 arithmetic operators(+,-,*,/, %) 优先级高于 boolean operators.

short-circuiting:
Logical expressions have corresponding evaluation procedures. These procedures exploit the fact that the truth value of a logical expression can sometimes be determined without evaluating all of its subexpressions, a feature called short-circuiting.
short-circuiting 是逻辑判断语句的一个重要特性, and, or 表达式有自己独特但类似的 short-circuiting.
To evaluate the expression <left> and <right>:
    Evaluate the subexpression <left>.
    If the result is a false value v, then the expression evaluates to v.
    Otherwise, the expression evaluates to the value of the subexpression <right>.

To evaluate the expression <left> or <right>:
    Evaluate the subexpression <left>.
    If the result is a true value v, then the expression evaluates to v.
    Otherwise, the expression evaluates to the value of the subexpression <right>.

If and and or do not short-circuiting, they just return the last value. This means that and and or don't always return booleans when using truth-y and false-y values.
>>>True and 13
13
>>>False or 0
0
>>>True and 0
0
>>>False or 1
1
>>>0 or False or 2 or 1/0
2

一个function中的 return 语句会终止这个 function. return 与 print 是不同的:
def t():
    print('huge')
    print("huge")
    return 'big'
    print('small')
    print('nothing')


10.png (3.53 KB, 下载次数: 5)

运行结果

运行结果
回复

使用道具 举报

🔗
 楼主| lh6210 2015-10-28 16:24:02 | 只看该作者
全局:
本帖最后由 lh6210 于 2015-10-28 16:26 编辑

disscution 1:   control section
1.3 question1
  1. def wears_jacket(temp, raining):
  2.     """
  3.     >>> rain = False
  4.     >>> wears_jacket(90, rain)
  5.     False
  6.     >>> wears_jacket(40, rain)
  7.     True
  8.     >>> wears_jacket(100, True)
  9.     True
  10.     """
  11.     return temp < 60 or raining== True
复制代码
solution 更为简洁:  return temp <60 or raining

1.3 question2
  1. def  handle_overflow(s1, s2):
  2.     """
  3.     >>> handle_overflow(27, 15)
  4.     No overflow.
  5.     >>> handle_overflow(35, 29)
  6.     1 spot left in Section 2.
  7.     >>> handle_overflow(20, 32)
  8.     10 spots left in Section 1.
  9.     >>> handle_overflow(35, 30)
  10.     No space left in either section.
  11.     """
  12.     if s1 < 30 and s2<30:
  13.         print('No overflow.')
  14.     elif s1 <30 <= s2:
  15.         left = 30- s1
  16.         if left==1:
  17.             print('1 spot left in Section 1.')
  18.         else:
  19.             print(left, 'spots left in Section 1.')
  20.     elif s2< 30<= s1:
  21.         left = 30- s2
  22.         if left ==1:
  23.             print('1 spot left in Section 2.')
  24.         else:
  25.             print(left, 'spots left in Section 2.')
  26.     else:
  27.         print('No space left in either section.')
复制代码
按照solution 的写法,在  python -m doctest ** 时会报错,问题出在  1 spots left in Section x. 与注释中  1 spot left in Section x不同。
def  handle_overflow(s1, s2):
    """
    >>> handle_overflow(27, 15)
    No overflow.
    >>> handle_overflow(35, 29)
    1 spot left in Section 2.
    >>> handle_overflow(20, 32)
    10 spots left in Section 1.
    >>> handle_overflow(35, 30)
    No space left in either section.
    """
    if s1<=30 and s2<=30:
        print("No overflow.")
    elif s2>30 and s1<30:
        print(str(30-s1)+" spots left in Section 1.")
    elif s1>30 and s2<30:
        print(str(30-s2)+" spots left in Section 2.")
    else:
        print("No space left in either section.")

1.6  question2
  1. def choose(n,k):
  2.     def f1(x):
  3.         total =1
  4.         while x>0:
  5.             total, x = total * x, x-1
  6.         return total
  7.     return f1(n)//(f1(k)*f1(n-k))
复制代码
solution 也挺不错:
def choose(n,k):
    total, i =1, 0
    while i<k:
        total = total * (n-i)// (i+1)
        i +=1
    return total

















回复

使用道具 举报

🔗
 楼主| lh6210 2015-10-29 13:06:28 | 只看该作者
全局:
discussion 1:  HOF section
2.2  question 2
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
"""
"""Enter your code"""
  1. def keep_ints(cond, n):
  2.     i =1
  3.     while i<=n:
  4.         if cond(i):
  5.             print(i)
  6.         i +=1

  7. def is_even(n):
  8.     return n%2==0
复制代码
2.4  question 2
改写上面的程序,达到  keep_ints(10)(is_even) == keep_ints(is_even, 10) 的效果。
  1. def is_even(n):
  2.     return n%2==0

  3. def keep2_ints(n):
  4.     def f(g):
  5.         i=1
  6.         while i<=n:
  7.             if g(i) is True:
  8.                 print(i)
  9.             i +=1
  10.     return f
复制代码
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表