CS61A Lab 1: 变量,方法和控制对象 Variables & Functions, Control

200 阅读2分钟

不得不说,CS61A的作业是真硬啊,一个LAB我做了一晚上。测试题目的话就不贴了。老教授好像还没教到debugger的那一块,所以error测试的时候,其实半懂不懂的.

所以直接贴题目了,有些题目,我觉得应该有更好的写法.我写的繁琐的紧了.

01 falling n数之积;

def falling(n, k):
    """Compute the falling factorial of n to depth k.
​
    >>> falling(6, 3)  # 6 * 5 * 4
    120
    >>> falling(4, 3)  # 4 * 3 * 2
    24
    >>> falling(4, 1)  # 4
    4
    >>> falling(4, 0)
    1
    """
    "*** YOUR CODE HERE ***"

这一题,我写了很久.这题最重要的点在于k的值从什么时候终止.我一直就想k -= 1的方式去做,但是试了好几次,都不行,只好加了一个临时变量了;

def falling(n, k):
    """Compute the falling factorial of n to depth k.
​
    >>> falling(6, 3)  # 6 * 5 * 4
    120
    >>> falling(4, 3)  # 4 * 3 * 2
    24
    >>> falling(4, 1)  # 4
    4
    >>> falling(4, 0)
    1
    """
    "*** YOUR CODE HERE ***"
    total = 1
    if not k:
        return 1
    else:
        counter = 0
        while k - counter:
            total *= n  # 6 5 4
            n -= 1
            counter += 1  # 1 2 3
    return total

02 sum_digits 各位数之和

def sum_digits(y):
    """Sum all the digits of y.
​
    >>> sum_digits(10) # 1 + 0 = 1
    1
    >>> sum_digits(4224) # 4 + 2 + 2 + 4 = 12
    12
    >>> sum_digits(1234567890)
    45
    >>> a = sum_digits(123) # make sure that you are using return rather than print
    >>> a
    6
    """
    "*** YOUR CODE HERE ***"

这题就不复杂了,只要取余求出各位数的值,然后相加就行了,但是有个问题就是10,因为10/10 = 0 的原因,需要考虑这种特殊情况;其余的迭代就行.

def sum_digits(y):
    """Sum all the digits of y.
​
    >>> sum_digits(10) # 1 + 0 = 1
    1
    >>> sum_digits(4224) # 4 + 2 + 2 + 4 = 12
    12
    >>> sum_digits(1234567890)
    45
    >>> a = sum_digits(123) # make sure that you are using return rather than print
    >>> a
    6
    """
    "*** YOUR CODE HERE ***"
    sum_t = 0
    while y:
        if y == 1:
            sum_t += 1
        else:
            sum_t += y % 10
        y = y // 10
    return sum_t

03 double_eights 判断连续两个值是否都为8;

def double_eights(n):
    """Return true if n has two eights in a row.
    >>> double_eights(8)
    False
    >>> double_eights(88)
    True
    >>> double_eights(2882)
    True
    >>> double_eights(880088)
    True
    >>> double_eights(12345)
    False
    >>> double_eights(80808080)
    False
    """
    "*** YOUR CODE HERE ***"

这一题,我原来的做法是

if n % 10 == 8 and n % 100 == 8: # 这种判断88 % 100 的时候余数应该是88.这种写法是错误的;

正确写法是这样,虽然复杂,但是能通过;

def double_eights(n):
    """Return true if n has two eights in a row.
    >>> double_eights(8)
    False
    >>> double_eights(88)
    True
    >>> double_eights(2882)
    True
    >>> double_eights(880088)
    True
    >>> double_eights(12345)
    False
    >>> double_eights(80808080)
    False
    """
    "*** YOUR CODE HERE ***"
    while n:
        if n % 10 == 8:
            y = n // 10
            if y % 10 == 8:
                return True
        n = n // 10
​
    return False

最后,补个截图.第一次lab通过了:

LAB_01.png