[2021 Spring] CS61A discussion 1 Environment Diagrams, Control

讨论部分代码:

# Q1: Jacket Weather?

def wears_jacket_with_if(temp, raining):
    """
    >>> wears_jacket_with_if(90, False)
    False
    >>> wears_jacket_with_if(40, False)
    True
    >>> wears_jacket_with_if(100, True)
    True
    """
    "*** YOUR CODE HERE ***"
    if temp < 60 or raining:
        return True
    else:
        return False

# a single line
def wears_jacket(temp, raining):
    "*** YOUR CODE HERE ***"
    return temp < 60 and raining

# Q2: (Tutorial) Warm Up: Case Conundrum

def special_case():
    x = 10
    if x > 0:
        x += 2
    elif x < 13:
        x += 3
    elif x % 2 == 1:
        x += 4
    return x

special_case() # 运行if后不会判断elif。 12

def just_in_case():
    x = 10
    if x > 0:
        x += 2
    if x < 13:
        x += 3
    if x % 2 == 1:
        x += 4
    return x

just_in_case() # 19

def case_in_point():
    x = 10
    if x > 0:
        return x + 2
    if x < 13:
        return x + 3
    if x % 2 == 1:
        return x + 4
    return x

case_in_point() # 12

# when using a series of if statements has the same effect 
# as using both if and elif cases 
# if语句直接return时

# Q3: Square So Slow
'''
def square(x):
    print("here!")
    return x * x

def so_slow(num):
    x = num
    while x > 0:
        x=x+1
    return x / 0
square(so_slow(5)) # 死循环
'''

# Q4: (Tutorial) Is Prime?

def is_prime(n):
    """
    >>> is_prime(10)
    False
    >>> is_prime(7)
    True
    """
    "*** YOUR CODE HERE ***"
    k = 2
    while n > k:
        if n % k == 0:
            return False
        k += 1
    return True

# Q5: (Tutorial) Fizzbuzz

def fizzbuzz(n):
    """
    >>> result = fizzbuzz(16)
    1
    2
    fizz
    4
    buzz
    fizz
    7
    8
    fizz
    buzz
    11
    fizz
    13
    14
    fizzbuzz
    16
    >>> result == None
    True
    """
    "*** YOUR CODE HERE ***"
    k = 1
    while k <= n:
        if k % 3 == 0 and k % 5 == 0:
            print('fizzbuzz')
        elif k % 3 == 0:
            print('fizz')
        elif k % 5 == 0:
            print('buzz')
        else:
            print(k)
        k += 1

Q6-Q9均为Environment Diagrams部分,拿不准的可以在python tutor自己试试。

下一项是课程第一个项目 Project 1: The Game of Hog

posted @ 2021-05-26 20:41  ikventure  阅读(782)  评论(0编辑  收藏  举报