CS 61A 2018Spring Week2 学习记录

这篇博客记录了CS 61A课程第二周的学习内容,主要涉及Python中的布尔值操作,包括逻辑运算符的优先级、逻辑短路现象。此外,博主还分享了在Lab 01中遇到的问题及改进的代码,如简化函数实现、修复bug等,展示了从Q3到Q11的题目解答和优化后的解决方案。
摘要由CSDN通过智能技术生成

知识点

1.布尔值

Boolean Operations — and, or, not

运算符(Operation) 计算结果(Result) 优先级
x or y if x is false, then y, else x (1)
x and y if x is false, then x, else y (2)
not x if x is false, then True, else False (3)

逻辑运算符优先级,not 最高,and 第二, or 第三。
not 运算符优先级低于其它非逻辑运算符,not a == b 相当于 not (a == b),如果写成 a == not b 就会报语法错误。

逻辑短路,计算2个值和一个逻辑运算符组成的表达式。
x or y 只有当 bool(x) 为False时,才会计算后面的y,否则直接得出表达式的值。
下面的代码发生短路情况,0为除数不合法,但发生短路,3/0没有被计算。

>>> 1 or 3 / 0   
1

x and y 只有当 bool(x) 为True时,才会计算后面的y。
下面的代码发生短路情况

>>> 0 and 3 / 0
0

下面这样的表达式为啥不发生短路。为啥结果不是0,而是[]

>>> 0 and 3 / 0 or None and 1 or []
[]

逻辑短路,计算2个值和一个逻辑运算符组成的表达式,0 and 3 / 0 发生了短路,0 and 3 / 0计算结果为0,但整个表达式求值没有完。
没有not,所有计算优先级最高的and,一共有两部分

0 and 3 / 00
None and 1None

此时整理成

0 or None or []

此时优先级相同,继续按顺序计算
首先计算

0 or NoneNone

最后计算

None or [][]

最后结果为[]

第二个纠结是:

>>> 3 and 4
4

文档上说了x and y if x is false, then x, else y。

2.代码习惯

lab01中Q3-Q5三个题写的像屎一样。
我发现我有一个啰嗦的习惯,就是把参数的值赋值给一个变量,而不是直接使用参数,

Lab 01

Q3: Repeated

Implement the repeated function, which takes a one-argument function f, a positive integer n, and a parameter x. It returns the result of composing, or applying, f n times on x, i.e., f(f(...f(x)...)).

def repeated(f, n, x):
    """Returns the result of composing f n times on x.

    >>> def square(x):
    ...     return x * x
    ...
    >>> repeated(square, 2, 3)  # square(square(3)), or 3 ** 4
    81
    >>> repeated(square, 1, 4)  # square(4)
    16
    >>> repeated(square, 6, 2)  # big number
    18446744073709551616
    >>> def opposite(b):
    ...     return not b
    ...
    >>> repeated(opposite, 4, True)
    True
    >>> repeated(opposite, 5, True)
    False
    >>> repeated(opposite, 631, 1)
    False
    >>> repeated(opposite, 3, 0)
    True
    """
    "*** YOUR CODE HERE ***"

我的答案

def repeated(f, n, x):
    count = 1
    answer = x
    while count <= n:
        count = count + 1
        answer = f(answer)
    return answer

更好的答案

def repeated(f, n, x):
    while n > 0:
        x = f(x)
        n -= 1
    return x
Q4: Sum Digits
def sum_digits(n):
    """Sum all the digits of n.

    >>> sum_digits(10) # 1 + 0 = 1
    1
    &
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值