08-CS-UY 1114 Lab 8
Functions
You must get checked out by your lab CA prior to leaving early. If you leave without being checked out, you will receive 0 credits for the lab.
你必须在离开之前得到你的实验室CA的检查。如果你没有被检查就离开,你将得到0学分的实验室。
Restrictions
限制
The Python structures that you use in this lab should be restricted to those you have learned in lecture so far. Please check with your teaching assistants in case you are unsure whether something is or is not allowed!
你在本实验中使用的 Python 结构应该仅限于你在课堂上所学到的。如果你不确定某些内容是允许的还是不允许的,请向你的助教询问!
Create a new python file for each of the following problems.
为以下每个问题创建一个新的 python 文件。
Your files should be named _lab[num]q[num].py
similar to homework naming conventions.
您的文件应该命名为
_lab[num]q[num].py
,类似于作业命名惯例。
Problem 1: Function Fun!
问题1:功能乐趣!
Write the outputs of the following code snippets by hand.
手写以下代码段的输出。
def mystery(num, string):
secret = ""
for char in string:
secret += char * num
return secret
def main():
print(mystery(5, "hello"))
main()
Answer 1.1
hhhhheeeeellllllllllooooo
def func_one(val):
num = 10
if val % 3 == 0:
print(num)
print("whoop")
return True
def func_two(num):
while num < 20:
if func_one(num):
print(num)
num += 1
print(num)
def main():
func_two(13)
main()
Answer 1.2
10
whoop
15
10
whoop
18
20
Problem 2: Et Tu, Programmator?
问题2:一个tu,程序员?
Write a function called decode_caesar that will accept encoded_message, a string containing a message encoded using a Caesar Cipher, and key, which is the shift that will be used to decode the message.
编写一个名为decode_caesar的函数,该函数将接受encoded_message,一个包含使用Caesar Cipher和key编码的消息的字符串,key是将用于解码消息的移位。
The Caesar cipher works as follows. Let's say we have the following snippet of the lyrics to Electric Light Orchestra's 1985 hit, "Calling America":
Caesar 密码的工作原理如下。假设我们有以下电光管弦乐队1985年的热门歌曲《呼唤美国》的歌词片段:
Talk is cheap on satellite
But all I get is static information
I'm still here
Re-dial on automatic
If we wanted to encode this using the Caeser cipher, with a key of (for example) 3. We would shift each letter's alphabetical index by 3 steps (i.e. "a" has an alphabetical index of 1, so if we shift it by 3, we'd get 4, or "d", "b" has an alphabetical index of 2, etc.). These are the lyrics encoded:
如果我们想使用凯撒密码对其进行编码,密钥为(例如)3。我们将移动每个字母的字母索引3步(即。“a”的字母下标是1,所以如果我们把它平移3,我们就得到4,或者“d”,“b”的字母下标是2,等等)。这些是歌词编码:
Wdon lv fkhds rq vdwhoolwh
Exw doo L jhw lv vwdwlf lqirupdwlrq
L'p vwloo khuh uh-gldo rq dxwrpdwlf
Your job is to decode encrypted messages like this, and return the decoded, original message.
您的工作就是像这样解码加密消息,并返回解码后的原始消息。
Here is a sample main function that you can use to test your code.
下面是一个示例 main 函数,您可以使用它来测试代码。
def main():
"""
Just some sample behavior.
"""
decryption_key = 3
line = input("Enter the encoded line: ")
decryption = decode_caesar(line, decryption_key)
print(decryption)
main()
My recommendation is to define a separate function that decrypts a single letter. Then, you can create a new, decoded string letter by letter.
我的建议是定义一个单独的函数来解密单个字母。然后,您可以逐字母创建一个新的解码字符串。
Note the following:
注意事项:
- Your program should be case-sensitive. That is, if our decoding key is 3,
"D"
shifts to"A"
and"d"
shifts to"a"
.
您的程序应该区分大小写。也就是说,如果我们的解码键是3,“D”就会移动到“A”,“D”也会移动到“A”。
- You may assume that you will always know the value of the decryption key.
您可以假设您总是知道解密密钥的值。
Your program should only shift characters that belong to the English dictionary. As such, you may assume the encoded message will be in English. (Caesar would have likely disapproved of this)
您的程序应该只移位属于英语字典的字符。因此,您可以假设编码的消息将是英语的。(恺撒很可能不赞成这样做)
Naturally, any modules that decode the Caesar cipher (of which I am sure there is at least one), are forbidden in this problem. Everything must be done manually, letter by letter, by you.
当然,在这个问题中,任何解码凯撒密码的模块(我确信至少有一个)都是被禁止的。每件事都必须手工完成,一个字一个字,由你来完成。
HINT: The usefulness of ord
and chr
is likely obvious, but %
(the modulus operator) will also come in very handy. To understand why, consider the instance of shifting "x"
, "y"
, or "z"
when the decryption key is 3. As there is no letter after "z"
, we must "rotate" back to "a"
. A look at the Caeser cipher's wiki page (linked above) might help make this clear as well.
提示:' ord '和' chr '的用处可能是显而易见的,但是' % '(模运算符)也非常方便。要理解其中的原因,请考虑当解密密钥为3时移动' ' x ' ', ' ' y ' '或' ' z ' '的实例。由于“z”后面没有字母,我们必须“旋转”回“a”。看一看凯撒密码的维基页面(上面有链接)可能也有助于弄清楚这一点。
Problem 3: Roman Code(r):
问题3:罗马法典(r):
You have been sent back in time, and are now working for the secret service in Ancient Rome. Currently, Rome is at war. One day, Roman soldiers intercepted a messenger delivering a written message to the enemy. However, the message seems to be encoded. As the brightest agent in the empire, you are tasked to find out what the message says. This is the message:
你被送回了过去,现在为古罗马的秘密机构工作。目前,罗马正处于战争之中。一天,罗马士兵拦截了一个向敌人传递书面信息的信使。然而,这条信息似乎是经过编码的。作为帝国中最聪明的特工,你的任务是找出信息的内容。这就是讯息:
3Gn.olwo pd/Q gh5l!d pulAk c_kosk an2 moPn! .y\oausr? 3mqei,sd+ktcbe.KrkcmOpsne!seodYpqo>kulq fag pozrtks dftpqh /ipaslk!dp4vm fkofwolp9 mjcnre
Before you start cracking the code, a fellow agent tells you that they managed to figure out how to decode the message from the captured messenger after some "light persuasion". According to the messenger, you can decoded the message by following these rules:
在你开始破解密码之前,一名特工同事告诉你,他们在经过一些“轻微的劝说”后,设法弄清楚了如何破译被捕信使的信息。根据信使的说法,你可以按照以下规则来解码消息:
- The message is separated into multiple parts, with each part starting with a number. Let's call this number N.
该消息被分成多个部分,每个部分都以一个数字开头。我们称这个数为N。
- Within each part, starting from the first character after N, keep every N'th character and remove the rest. For example,
2hfik
would behi
(start with h and skip every other character).
在每个部分中,从N后面的第一个字符开始,保留第N个字符并删除其余的字符。例如,2hfik将是hi(从h开始,跳过所有其他字符)。
- The original message stops after 100 letters have been processed in the encoded message (so you only have to decode the first 100 alphabetical characters of the message). If the 100 letter limit is reached in the middle of a part, you can ignore that entire part.
在编码消息中处理了100个字母后,原始消息停止(因此只需解码消息的前100个字母字符)。如果在某个部分的中间达到了100个字母的限制,则可以忽略整个部分。
After learning this, like any genius tactician in Ancient Rome, you decide to write a computer program to tell you the decoded message. As a wise man once said, you can split this problem into 2 functions:
在了解到这一点后,你就像古罗马的天才战术家一样,决定编写一个计算机程序来告诉你解码后的信息。一位智者曾经说过,你可以把这个问题分解成两个函数:
- Write a function to decoded each part. This function should take in the following parameters: the entire message, where the part starts, where the part ends, and what the number (N) is for that part, and returns a decoded string.
编写函数对各部分进行解码。这个函数应该接受以下参数:整个消息,部分从哪里开始,部分在哪里结束,以及该部分的数字(N)是什么,并返回一个解码后的字符串。
- Write a function that splits the messages into different parts, and use the first function you wrote to decode the part. Remember that each part starts with a number. You also need to make sure to stop decoding after your have counted 100 letters. The function should return the entire decoded message.
编写一个函数,将消息拆分为不同的部分,并使用您编写的第一个函数来解码该部分。记住,每个部分都以数字开头。您还需要确保在数到100个字母后停止解码。该函数应该返回整个解码后的消息。
Hints:
提示:
- For the first function, you are giving the start, end, and a step as parameters. What have you learned that might use all 3 of these?
对于第一个函数,您将开始、结束和步骤作为参数。你学到了什么可以用到这三种方法?
- For the second function, you need to look at each character in the encoded message, so you would need to loop through the message. However, you need to stop after encountering 100 letters, so you must check if the character you are currenetly looking at is a letter in every step of the loop. Which of the different types of loops you've learned is most useful here?
对于第二个函数,您需要查看编码消息中的每个字符,因此您需要对消息进行循环。然而,你需要在遇到100个字母后停下来,所以你必须在循环的每一步中检查你当前看到的字符是否是一个字母。你学过的不同类型的循环在这里最有用?
- Since you are calling the first function in your second function, you need to obtain all the paramters for the first function. You can use the same message as the first paramter, but you will need to obtain the start, end, and step parameters. Think about which of these need to be initialized, and when they need to be updated.
由于要在第二个函数中调用第一个函数,因此需要获取第一个函数的所有参数。您可以使用与第一个参数相同的消息,但是您需要获得开始、结束和步骤参数。考虑哪些需要初始化,以及何时需要更新。
If your code is correct, you should see a readable message being printed.
如果您的代码是正确的,您应该看到打印了一条可读的消息。
Here is a sample main
function that you can use to test your code.
下面是一个示例 main 函数,您可以使用它来测试代码。
def main():
"""
Test your code here.
"""
message = "3Gn.olwo pd/Q gh5l!d pulAk c_kosk an2 moPn! .y\oausr?3mqei,sd+ktcbe.KrkcmOpsne!se odYpqo>kulq fag pozrtks dftpqh /ipaslk!dp4vmfkofwolp9 mjcnre"
print(decode_entire_msg(message))
Oh and one more thing. The agent tells you that the messenger said the message is from something called "CAs" to their students. Wonder what that could mean.
photo Answer


Problem 4: Reading With Numbers
问题4:数字阅读
Often times when a word is mispelled, our brain can still make sense of what we're reading. This phenomenon is unofficially recognized as Typoglycemia. For this problem, you will test the limits of Typoglycemia by prompting the user for text and changing the user's input to swap some characters with numbers L1K3 TH15 (like this).
通常情况下,当一个单词拼写错误时,我们的大脑仍然可以理解我们正在阅读的内容。这种现象被非正式地称为糖尿病。对于这个问题,您将测试Typoglycemia的限制,方法是提示用户输入文本,并更改用户的输入以将一些字符与数字L1K3 TH15交换(就像这样)。
Part A: Defining the Helper Function
第一部分:定义Helper函数
First define the numberify(word)
function. This function accepts a string message and returns an uppercase version of this message. Specific characters will be swapped out for numbers as so:
首先定义' numberify(word) '函数。这个函数接受一个字符串消息,并返回该消息的大写版本。特定的字符将被替换为数字,如下所示:
A -> 4
E -> 3
I -> 1
S -> 5
T -> 7
O -> 0
"""
Returns a numberified version of the passed in string word
"""
def numberify(word):
# Code here
Part B: Prompting for User Input
第二部分:用户输入提示
In the main(),
prompt the user for a message to numberify. A word is numberified only if the word has a length greater than 3. You may assume each word will be separated by a single whitespace. You must use numberify()
in your solution.
在main()中,提示用户对消息进行编号。只有当单词的长度大于3时,单词才会被编号。你可以假设每个单词都用一个空格隔开。必须在解决方案中使用numberify()。
The following are examples of possible outputs:
以下是可能的输出示例:
Please enter a message to numberify: This message serves to prove how our minds can do amazing things
Your numberified string is: 7H15 M3554G3 53RV35 TO PR0V3 HOW OUR M1ND5 CAN DO 4M4Z1NG 7H1NG5
Please enter a message to numberify: In the beginning it was hard but your mind is reading it automatically with out even thinking about it
Your numberified string is: IN THE B3G1NN1NG IT WAS H4RD BUT Y0UR M1ND IS R34D1NG
IT 4U70M471C4LLY W17H OUT 3V3N 7H1NK1NG 4B0U7 IT
Answer
# -*- coding: utf-8 -*-
# @Time : 2023/3/28 09:35
# @Author : AI悦创
# @FileName: q4.py
# @Software: PyCharm
# @Blog :https://bornforthis.cn/
def numberify(word):
word = word.upper()
char_to_number = {'A': '4', 'E': '3', 'I': '1', 'S': '5', 'T': '7', 'O': '0'}
numberified_word = ""
for char in word:
if char in char_to_number:
numberified_word += char_to_number[char]
else:
numberified_word += char
return numberified_word
def main():
message = input("Please enter a message to numberify: ")
words = message.split()
numberified_message = []
for word in words:
if len(word) > 3:
numberified_message.append(numberify(word))
else:
numberified_message.append(word.upper())
result = ' '.join(numberified_message)
print("Your numberified string is:", result)
if __name__ == "__main__":
main()
# if __name__ == '__main__':
# r = numberify("This message serves to prove how our minds can do amazing things")
# print(r)
print("IN THE B3G1NN1NG IT WAS H4RD BUT Y0UR M1ND IS R34D1NG IT 4U70M471C4LLY W17H OUT 3V3N 7H1NK1NG 4B0U7 IT" ==
"IN THE B3G1NN1NG IT WAS H4RD BUT Y0UR M1ND IS R34D1NG IT 4U70M471C4LLY W17H OUT 3V3N 7H1NK1NG 4B0U7 IT")
def main():
message = input("Please enter a message to numberify: ")
words = []
current_word = ""
for char in message:
if char == " ":
if current_word:
words.append(current_word)
current_word = ""
else:
current_word += char
if current_word:
words.append(current_word)
numberified_message = []
for word in words:
if len(word) > 3:
numberified_message.append(numberify(word))
else:
numberified_message.append(word.upper())
result = ' '.join(numberified_message)
print("Your numberified string is:", result)
if __name__ == "__main__":
main()
# -*- coding: utf-8 -*-
# @Time : 2023/3/28 09:35
# @Author : AI悦创
# @FileName: q4.py
# @Software: PyCharm
# @Blog :https://bornforthis.cn/
def numberify(word):
word = word.upper()
char_to_number = {'A': '4', 'E': '3', 'I': '1', 'S': '5', 'T': '7', 'O': '0'}
numberified_word = ""
for char in word:
if char in char_to_number:
numberified_word += char_to_number[char]
else:
numberified_word += char
return numberified_word
def main():
message = input("Please enter a message to numberify: ")
child_word = ""
result = ""
for char in message:
if char == " ":
if len(child_word) > 3:
result = result + numberify(child_word) + " "
# result = result + child_word + " "
else:
result = result + child_word + " "
child_word = ""
# continue
else:
child_word += char
# print(child_word)
if len(child_word) > 3:
child_word = numberify(child_word)
result += child_word
result = result.upper()
print("Your numberified string is:", result)
if __name__ == "__main__":
main()
# -*- coding: utf-8 -*-
# @Time : 2023/3/28 09:35
# @Author : AI悦创
# @FileName: q4.py
# @Software: PyCharm
# @Blog :https://bornforthis.cn/
def numberify(word):
word = word.upper()
char_to_number = {'A': '4', 'E': '3', 'I': '1', 'S': '5', 'T': '7', 'O': '0'}
numberified_word = ""
for char in word:
if char in char_to_number:
numberified_word += char_to_number[char]
else:
numberified_word += char
return numberified_word
def main():
message = input("Please enter a message to numberify: ")
words = message.split()
# print(words)
result = ""
for word in words:
if len(word) > 3:
result = result + numberify(word) + " "
else:
result = result + word + " "
result = result.upper()[:-1]
print("Your numberified string is:", result)
if __name__ == "__main__":
main()
# -*- coding: utf-8 -*-
# @Time : 2023/3/28 09:35
# @Author : AI悦创
# @FileName: q4.py
# @Software: PyCharm
# @Blog :https://bornforthis.cn/
def numberify(word):
word = word.upper()
# char_to_number = {'A': '4', 'E': '3', 'I': '1', 'S': '5', 'T': '7', 'O': '0'}
target_char = 'AEISTO'
target_num = '431570'
numberified_word = ""
for char in word:
if char in target_char:
numberified_word += target_num[target_char.index(char)]
else:
numberified_word += char
return numberified_word
def main():
message = input("Please enter a message to numberify: ")
child_word = ""
result = ""
for char in message:
if char == " ":
if len(child_word) > 3:
result += numberify(child_word) + " "
else:
result += child_word + " "
child_word = ""
else:
child_word += char
if len(child_word) > 3:
child_word = numberify(child_word)
result += child_word
result = result.upper()
print("Your numberified string is:", result)
if __name__ == "__main__":
main()
Problem 5: Budgeting
问题5:预算
For this problem we will be writing 3 functions as follows.
对于这个问题,我们将编写如下3个函数。
def calculate_income(hourly_rate):
"""
Calculate weekly income based on hourly rate and hours worked
:param hourly_rate: the hourly pay rate used to calculate income
:return: float of total_pay
"""
calculate_income()
will calculate the weekly income of the user. We will assume the user works a standard 5 day work week and will input their whole number hours for each day. Furthermore, any hours worked over 40 hours is considered overtime and will be paid at 1.5 times the standard hourly rate.
Calculate_income() 将计算用户的周收入。我们假设用户每周工作5天,并输入他们每天的全部小时数。此外,任何超过40小时的工作时间都被视为加班,并将按标准时薪的1.5倍支付。
The output should appear as follows and the function shoulr return the total pay.
输出应该如下所示,函数应该返回总支付。
Enter the number of hours worked today: 5
Enter the number of hours worked today: 4
Enter the number of hours worked today: 12
Enter the number of hours worked today: 10
Enter the number of hours worked today: 10
def calculate_expenses():
"""
Calculate weekly expenses based on user input of expenses
:return: float of total expenses
"""
calculate_expenses()
function will calculate the total weekly expenses of the user. The user will enter floats of all money they spent in the week until they enter Q to quit.
Calculate_expenses()函数将计算用户每周的总开销。用户将输入他们在一周内花费的所有钱的浮动,直到他们输入Q退出。
Allow the user to enter all expenses as shown and return the total money they spent.
允许用户输入所示的所有费用,并返回他们花费的总金额。
Enter how much money you spent or Q if done: 23
Enter how much money you spent or Q if done: 22
Enter how much money you spent or Q if done: 100
Enter how much money you spent or Q if done: Q
def budget_outcome(income, expenses):
"""
Determine whether the user had a gain or loss over the week.
:param income: total amount of weekly income
:param expenses: total weekly expenses
:return: the difference between income and expenses
"""
The budget_outcome()
function should return the difference between income and expenses and print a message based on whether the user lost money or gained money over the week as shown.
budget_outcome() 函数应该返回收入和支出之间的差额,并根据用户在一周内是亏钱还是赚钱打印一条消息,如图所示。
Well done you had a gain of 477.5
You had a loss of -125.0
This main function is a nice way to test your code using all three functions.
这个main函数是使用这三个函数测试代码的好方法。
def main():
income = calculate_income(15)
expenses = calculate_expenses()
budget_outcome(income, expenses)
Answer 5
「待测试」
def calculate_income(hourly_rate):
"""
Calculate weekly income based on hourly rate and hours worked
:param hourly_rate: the hourly pay rate used to calculate income
:return: float of total_pay
"""
total_hours = 0
for i in range(5):
hours = int(input("Enter the number of hours worked today: "))
total_hours += hours
overtime_hours = max(0, total_hours - 40)
regular_hours = total_hours - overtime_hours
total_pay = (hourly_rate * regular_hours) + (hourly_rate * 1.5 * overtime_hours)
return total_pay
def calculate_expenses():
"""
Calculate weekly expenses based on user input of expenses
:return: float of total expenses
"""
total_expenses = 0
while True:
expense = input("Enter how much money you spent or Q if done: ")
if expense.lower() == "q":
break
total_expenses += float(expense)
return total_expenses
def budget_outcome(income, expenses):
"""
Determine whether the user had a gain or loss over the week.
:param income: total amount of weekly income
:param expenses: total weekly expenses
:return: the difference between income and expenses
"""
difference = income - expenses
if difference > 0:
print(f"Well done, you had a gain of {difference:.2f}")
else:
print(f"You had a loss of {difference:.2f}")
return difference
def main():
hourly_rate = float(input("Enter your hourly rate: "))
income = calculate_income(hourly_rate)
expenses = calculate_expenses()
budget_outcome(income, expenses)
if __name__ == "__main__":
main()
def calculate_income(hourly_rate):
"""
计算基于小时工资和工作小时数的每周收入
:param hourly_rate: 用于计算收入的小时工资
:return: total_pay的浮点数
"""
total_hours = 0
# 循环5次,分别表示一周的5个工作日
for i in range(5):
# 获取用户输入的每天工作小时数
hours = int(input("Enter the number of hours worked today: "))
# 将每天的工作小时累加到总小时数
total_hours += hours
# 计算加班小时数(超过40小时的部分)
overtime_hours = max(0, total_hours - 40)
# 计算常规工作小时数(总小时数减去加班小时数)
regular_hours = total_hours - overtime_hours
# 计算总收入(常规小时工资 + 加班小时工资)
total_pay = (hourly_rate * regular_hours) + (hourly_rate * 1.5 * overtime_hours)
return total_pay
def calculate_expenses():
"""
根据用户输入的支出计算每周总支出
:return: 总支出的浮点数
"""
total_expenses = 0
while True:
# 获取用户输入的支出金额,如果输入为 "Q",则结束循环
expense = input("Enter how much money you spent or Q if done: ")
if expense.lower() == "q":
break
# 将支出累加到总支出中
total_expenses += float(expense)
return total_expenses
def budget_outcome(income, expenses):
"""
判断用户在一周内是盈利还是亏损
:param income: 每周总收入
:param expenses: 每周总支出
:return: 收入与支出之间的差额
"""
difference = income - expenses
if difference > 0:
print(f"干得好,你盈利了 {difference:.2f}")
else:
print(f"你亏损了 {difference:.2f}")
return difference
def main():
# 获取用户输入的小时工资
hourly_rate = float(input("Enter your hourly rate: "))
# 计算每周收入
income = calculate_income(hourly_rate)
# 计算每周支出
expenses = calculate_expenses()
# 根据收入和支出判断用户是盈利还是亏损
budget_outcome(income, expenses)
if __name__ == "__main__":
main()
为什么使用 overtime_hours = max(0, total_hours - 40)
,也就是使用 max 实现超过部分?
使用 overtime_hours = max(0, total_hours - 40)
是为了确保当 total_hours
小于或等于 40 时,overtime_hours
的值为 0。这是因为在这种情况下,没有加班小时需要计算。
max()
函数返回两个参数中的最大值。当 total_hours
大于 40 时,total_hours - 40
将计算出加班小时数。而当 total_hours
小于或等于 40 时,total_hours - 40
的结果将是负数,但是我们希望加班小时数为 0。因此,我们使用 max(0, total_hours - 40)
来确保加班小时数始终是非负数。
举例来说:
- 如果
total_hours = 45
,那么overtime_hours = max(0, 45 - 40) = max(0, 5) = 5
。这里,加班小时数为 5 小时。 - 如果
total_hours = 38
,那么overtime_hours = max(0, 38 - 40) = max(0, -2) = 0
。这里,没有加班小时数。
公众号:AI悦创【二维码】

AI悦创·编程一对一
AI悦创·推出辅导班啦,包括「Python 语言辅导班、C++ 辅导班、java 辅导班、算法/数据结构辅导班、少儿编程、pygame 游戏开发、Web、Linux」,全部都是一对一教学:一对一辅导 + 一对一答疑 + 布置作业 + 项目实践等。当然,还有线下线上摄影课程、Photoshop、Premiere 一对一教学、QQ、微信在线,随时响应!微信:Jiabcdefh
C++ 信息奥赛题解,长期更新!长期招收一对一中小学信息奥赛集训,莆田、厦门地区有机会线下上门,其他地区线上。微信:Jiabcdefh
方法一:QQ
方法二:微信:Jiabcdefh
