实验 05 循环

实验 05 循环

一、实验目的

  • 掌握for循环的使用方法
  • 掌握while循环的使用方法

二、实验环境

  • Jupter Notebook

三、实验内容

1.(20分)

你有没有觉得调试需要一点运气?以下程序有一个错误。尝试识别错误并修复它。

def has_lucky_number(nums):
    """返回给定的数字列表是否幸运。幸运名单至少包含一个可以被7整除的数字。
    """
    for num in nums:
        if num % 7 == 0:
            return True
        else:
            return False

尝试识别错误并在下面的单元格中修复它:

def has_lucky_number(nums):
    for num in nums:
        if num % 7 == 0:
            return True
    # We've exhausted the list without finding a lucky number
    return False

2.(20分)

a.(10分)

看看下面的Python表达式。你认为我们运行它会得到什么?当您做出预测后,请取消对代码的注释并运行单元格以查看是否正确。

#[1, 2, 3, 4] > 2

预测一下运行结果:

list和int不能进行比较

b.(10分)

Python有一些库(比如numpy和pandas)将列表中的每个元素与2进行比较(即进行“元素方面的”比较),并给我们一个布尔值列表,比如[False, False, True, True]

实现一个重现此行为的函数,返回对应于相应元素是否大于n的布尔值列表。

def elementwise_greater_than(L, thresh):
    """返回一个与L长度相同的列表,如果L[i]大于thresh,则索引i处的值为True,否则为False。
    
    >>> elementwise_greater_than([1, 2, 3, 4], 2)
    [False, False, True, True]
    """
    pass

完成后的函数如下:

def elementwise_greater_than(L, thresh):
    res = []
    for ele in L:
        res.append(ele > thresh)
    return res

3.(30分)

根据函数的docstring完成下面的函数体。
提示:在这种情况下,最好迭代列表的索引(使用range()),而不是迭代列表本身的元素。当索引到列表中时,请注意不要“掉队”(即使用不存在的索引)。

def menu_is_boring(meals):
    """如果一段时间内提供了一份餐清单,如果同一顿饭连续两天供应,则返回True,否则为假。
    """
    pass

完成后的函数如下:

def menu_is_boring(meals):
    # Iterate over all indices of the list, except the last one
    for i in range(len(meals)-1):
        if meals[i] == meals[i+1]:
            return True
    return False

猜你喜欢

转载自blog.csdn.net/m0_68111267/article/details/131397558
今日推荐