【数据科学导论】实验三:布尔变量与条件语句

简介: 【数据科学导论】实验三:布尔变量与条件语句

布尔变量与条件语句

实验目的

  • 掌握布尔型变量的使用方法
  • 掌握比较运算符与比较表达式
  • 掌握逻辑运算符与逻辑表达式
  • 掌握条件语句的使用
  • 布尔类型转换

实验设备

  • Jupter Notebook

实验内容

1. (15分)

许多编程语言都有sign作为内置函数提供。Python没有,但是我们可以定义自己的!

在下面的单元格中,定义一个名为“sign”的函数,该函数接受一个数值参数,如果为负,则返回-1;如果为正,则返回1;如果为0,则返回0。

# Your code goes here. Define a function called 'sign'
def sign(x):
    if x > 0:
        return 1
    elif x < 0:
        return -1
    else:
        return 0

函数测试

# put your test code here
sign(-3)
-1


2. (15分)

我们决定将"logging"添加到上一个练习中的to_smash函数中。

def to_smash(total_candies):
    """返回在3个朋友之间平均分配给定数量的糖果后必须砸碎的剩余糖果数量。
    >>> to_smash(91)
    1
    """
    print("Splitting", total_candies, "candies")
    return total_candies % 3
to_smash(91)
Splitting 91 candies
1

total_candies = 1时,调用函数时会发生什么情况呢?

to_smash(1)
Splitting 1 candies
1

这可不是什么好语法!

修改下面单元格中的定义以更正print语句的语法。(如果只有一个糖果,我们应该用单数的“candy”代替复数的“candies”)

def to_smash(total_candies):
    """Return the number of leftover candies that must be smashed after distributing
    the given number of candies evenly between 3 friends.
    >>> to_smash(91)
    1
    """
    if total_candies == 1:
        print("Splitting 1 candy")
    else:
        print("Splitting", total_candies, "candies")
    return total_candies % 3

函数测试

to_smash(1)
Splitting 1 candy
1

3. 🌶️(20分)

在主课中,我们讨论了决定是否准备好迎接天气。我说我不会受今天的天气影响,如果…

  • 如果我有伞…
  • 或者如果雨不是太大,我有个帽子…
  • 否则,我还是很好,除非下雨,而且是工作日

下面的函数使用我们首次尝试将此逻辑转换为Python表达式。代码中有一个bug。你能找到吗?

为了证明“为天气做好准备”是有缺陷的,可以提出一组输入,其中:

  • 函数返回False(但应该返回True),或者
  • 函数返回True(但应该返回False)。

要解决这个问题,代码应返回正确的结果。

提示:看看我们在主课中是如何修正原始表达式的。我们在某些子表达式周围加了括号。这段代码中的错误是由Python以“错误”的顺序计算某些操作引起的。

def prepared_for_weather(have_umbrella, rain_level, have_hood, is_workday):
    # Don't change this code. Our goal is just to find the bug, not fix it!
    return have_umbrella or rain_level < 5 and have_hood or not rain_level > 0 and is_workday
# 修改相应的变量取值,证明prepared_for_weather
# 函数中的逻辑表达式是有bag的
have_umbrella = True
rain_level = 0.0
have_hood = True
is_workday = True
# Check what the function returns given the current values of the variables above
actual = prepared_for_weather(have_umbrella, rain_level, have_hood, is_workday)
print(actual)
True

修改后的变量取值及函数调用结果

# 修改相应的变量取值,证明prepared_for_weather
# 函数中的逻辑表达式是有bag的
have_umbrella = False
rain_level = 0.0
have_hood = False
is_workday = False
# Check what the function returns given the current values of the variables above
actual = prepared_for_weather(have_umbrella, rain_level, have_hood, is_workday)
print(actual)
False

试分析错误原因,并修改prepared_for_weather函数中的逻辑表达式

错误原因:

很明显,我们已经做好了应对天气的准备。没有下雨。不仅如此,今天不是工作日,所以我们甚至不需要离开家!但是我们的函数基于这些输入返回为False,显然是不合理的。

问题出在逻辑表达式的后半部分,按照运算次序会执行and运算,后执行not运算,相当于:

not (rain_level > 0 and is_workday)

修改后的逻辑表达式

将逻辑表达式后半部分用括号改变一下运算次序:

have_umbrella or rain_level < 5 and have_hood or (not (rain_level > 0)) and is_workday

测试程序:

def prepared_for_weather(have_umbrella, rain_level, have_hood, is_workday):
    # Don't change this code. Our goal is just to find the bug, not fix it!
    return have_umbrella or rain_level < 5 and have_hood or (not (rain_level > 0)) and is_workday
# Change the values of these inputs so they represent a case where prepared_for_weather
# returns the wrong answer.
have_umbrella = False
rain_level = 0.0
have_hood = False
is_workday = False
# Check what the function returns given the current values of the variables above
actual = prepared_for_weather(have_umbrella, rain_level, have_hood, is_workday)
print(actual)
False

4.(15分)

The function is_negative below is implemented correctly - it returns True if the given number is negative and False otherwise.


However, it’s more verbose than it needs to be. We can actually reduce the number of lines of code in this function by 75% while keeping the same behaviour.


See if you can come up with an equivalent body that uses just one line of code, and put it in the function concise_is_negative. (HINT: you don’t even need Python’s ternary syntax)


下面的is_negative函数的功能是:如果给定的数字为负数,则返回True,否则返回False。


实际上,我们可以将此函数中的代码行数减少75%,同时保持相同的行为。


看看你能不能想出一个只使用1行代码的等价体,并把它放在函数concise_is_negative中。(提示:您甚至不需要Python的三元语法)

def is_negative(number):
    if number < 0:
        return True
    else:
        return False

修改后的结果

def concise_is_negative(number):
    return number < 0

测试程序

concise_is_negative(5)
False

5.(15分)

布尔变量 番茄酱(ketchup)芥末(mustard)洋葱(onion)代表顾客是否想要在他们的热狗上添加特定的配料。我们想要实现一些布尔函数,这些函数对应于关于客户订单的一些是或否问题。例如:

def onionless(ketchup, mustard, onion):
    """返回顾客是否不想要洋葱。
    """
    return not onion

对于其余的每个函数,请填写正文以匹配docstring中的描述。

a)

def wants_all_toppings(ketchup, mustard, onion):
    """返回客户是否需要“the works”(全部3种配料)
    """
    return ketchup and mustard and onion

b)

def wants_plain_hotdog(ketchup, mustard, onion):
    """返回客户是否想要没有配料的普通热狗。
    """
    return not ketchup and not mustard and not onion

c)

def exactly_one_sauce(ketchup, mustard, onion):
    """返回顾客想要番茄酱(ketchup)还是芥末(mustard),但不能两者都要。
    """
    return (ketchup and not mustard) or (mustard and not ketchup)

6. 🌶️(20分)

我们已经看到,对一个整数调用bool(),如果它等于0,则返回False;否则返回True。如果我们对布尔值调用int()会发生什么?在下面的Notebook Cell里试试看。

利用这一点写一个简洁的函数,来实现“顾客想要一种配料吗?”

def exactly_one_topping(ketchup, mustard, onion):
    """返回客户是否只想要三种热狗配料中的一种。
    """
    return (int(ketchup) + int(mustard) + int(onion)) == 1


目录
相关文章
|
11月前
|
索引 Python
【数据科学导论】实验五:循环
【数据科学导论】实验五:循环
54 0
|
3天前
|
C语言
C语言程序设计核心详解 第二章:数据与数据类型 4种常量详解 常见表达式详解
本文详细介绍了C语言中的数据与数据类型,包括常量、变量、表达式和函数等内容。常量分为整型、实型、字符型和字符串常量,其中整型常量有十进制、八进制和十六进制三种形式;实型常量包括小数和指数形式;字符型常量涵盖常规字符、转义字符及八进制、十六进制形式;字符串常量由双引号括起。变量遵循先定义后使用的规则,并需遵守命名规范。函数分为标准函数和自定义函数,如`sqrt()`和`abs()`。表达式涉及算术、赋值、自增自减和逗号运算符等,需注意运算符的优先级和结合性。文章还介绍了强制类型转换及隐式转换的概念。
R语言笔记丨从零学起?环境安装、基础知识、运算法则、数据类型(下)
R语言笔记丨从零学起?环境安装、基础知识、运算法则、数据类型(下)
|
4月前
|
存储 人工智能 Java
软件测试/人工智能|Python 变量解析:从基础概念到内存地址探究
软件测试/人工智能|Python 变量解析:从基础概念到内存地址探究
53 0
|
11月前
|
Python
【数据科学导论】实验一:语法、变量和数据类型
【数据科学导论】实验一:语法、变量和数据类型
86 0
|
11月前
【数据科学导论】实验六:字符串与字典
【数据科学导论】实验六:字符串与字典
31 0
|
11月前
|
Serverless Python
【数据科学导论】实验二:函数调用
【数据科学导论】实验二:函数调用
36 0
|
机器学习/深度学习 数据挖掘 Linux
R语言笔记丨从零学起?环境安装、基础知识、运算法则、数据类型(上)
R语言笔记丨从零学起?环境安装、基础知识、运算法则、数据类型
|
C语言 存储
带你读《C语言程序设计习题解析与上机指导》之三:数据类型、运算符与表达式
本书首先介绍了计算机程序设计实验的一般方法以及在Visual C++ 2010下编写和调试C语言程序的具体步骤,然后对主教材各章后面的习题以及C语言程序设计课程学习中的疑难问题和常见问题进行了详细的解析,同时还汇总了各章的知识重点。在第三部分,精心设置了9个上机实验,每个实验项目都给出了实验目的和要求,并给出了编程示例和练习题目。读者可以通过由浅入深的实际训练,逐步熟悉编程环境,掌握程序调试方法,理解和掌握程序设计的思想、方法和技巧。