课程:CS50’s Introduction to Programming with Python
CS50 Python 2025 课程的问题集作业提交。主要提供一个本人的解题思路,仅供参考。
Deep Thought
Problem:
“All right,” said the computer, and settled into silence again. The two men fidgeted. The tension was unbearable.“好吧,”电脑说,然后又陷入了沉默。两个人坐立不安。紧张感难以忍受。
“You’re really not going to like it,” observed Deep Thought.“你真的不会喜欢它,”深思熟虑说。
“Tell us!” “告诉我们!”
“All right,” said Deep Thought. “The Answer to the Great Question…”“好吧,”深思说。“这个伟大问题的答案……”
“Yes…!” “是的……!”
“Of Life, the Universe and Everything…” said Deep Thought.“关于生命、宇宙和一切……”深思说道。
“Yes…!” “是的……!”
“Is…” said Deep Thought, and paused.“是……”深思说道,停顿了一下。
“Yes…!” “是的……!”
“Is…” “是……”
“Yes…!!!…?” “是的……!! …?”
“Forty-two,” said Deep Thought, with infinite majesty and calm.”“四十二,”深思说,带着无限的威严和平静。— The Hitchhiker’s Guide to the Galaxy, Douglas Adams— 银河系漫游指南 ,道格拉斯·亚当斯
In deep.py, implement a program that prompts the user for the answer to the Great Question of Life, the Universe and Everything, outputting Yes if the user inputs 42 or (case-insensitively) forty-two or forty two. Otherwise output No.deep.py,实现一个程序,提示用户回答生命、宇宙和万物的伟大问题,如果用户输入 42 或(不区分大小写) 四十二或四十二 ,则输出 Yes。否则输出 No。
Submit:
answer = input("What is the Answer to the Great Question of Life, the Universe, and Everything? ")
if answer.replace(" ", "") == "42" or answer.lower() == "forty-two" or answer.lower() == "forty two":
print("Yes")
else:
print("No")
Home Federal Savings Bank
Problem:
In season 7, episode 24 of Seinfeld, Kramer visits a bank that promises to give $100 to anyone who isn’t greeted with a “hello.” Kramer is instead greeted with a “hey,” which he insists isn’t a “hello,” and so he asks for $100. The bank’s manager proposes a compromise: “You got a greeting that starts with an ‘h,’ how does $20 sound?” Kramer accepts.
在《 宋飞正传 》 第 7 季第 24 集中 , 克莱默拜访了一家银行,该银行承诺向任何没有打招呼“你好”的人提供 100 美元。相反,克莱默受到了“嘿”的欢迎,他坚称这不是“你好”,所以他要了 100 美元。银行经理提出了一个折衷方案:“你有一个以’h’开头的问候语,20 美元听起来怎么样?克莱默接受了。
In a file called bank.py, implement a program that prompts the user for a greeting. If the greeting starts with “hello”, output $0. If the greeting starts with an “h” (but not “hello”), output $20. Otherwise, output $100. Ignore any leading whitespace in the user’s greeting, and treat the user’s greeting case-insensitively.
在名为 bank.py 的文件中,实现一个提示用户打问候语的程序。如果问候语以“hello”开头,则输出 $0。如果问候语以“h”开头(但不是“hello”),则输出 $20。否则,输出 100 美元 。忽略用户问候语中的任何前导空格,并不区分大小写来处理用户的问候语。
Submit:
say = input("Greeting: ")
if say.lower().strip()[:5] == "hello":
print("$0")
elif say.lower().strip()[:1] == "h":
print("$20")
else:
print("$100")
File Extensions
Problem:
Even though Windows and macOS sometimes hide them, most files have file extensions, a suffix that starts with a period (.) at the end of their name. For instance, file names for GIFs end with .gif, and file names for JPEGs end with .jpg or .jpeg. When you double-click on a file to open it, your computer uses its file extension to determine which program to launch.
尽管 Windows 和 macOS 有时会隐藏它们,但大多数文件都有文件扩展名 ,即名称末尾以句点 (.) 开头的后缀。例如,GIF 的文件名以 .gif 结尾,JPEG 的文件名以 .jpg 或 .jpeg 结尾。当您双击文件以打开它时,您的计算机会使用其文件扩展名来确定要启动的程序。
Web browsers, by contrast, rely on media types, formerly known as MIME types, to determine how to display files that live on the web. When you download a file from a web server, that server sends an HTTP header, along with the file itself, indicating the file’s media type. For instance, the media type for a GIF is image/gif, and the media type for a JPEG is image/jpeg. To determine the media type for a file, a web server typically looks at the file’s extension, mapping one to the other.
相比之下,Web 浏览器依赖于媒体类型 (以前称为 MIME 类型)来确定如何显示 Web 上的文件。当您从 Web 服务器下载文件时,该服务器会发送一个 HTTP 标头以及文件本身,指示文件的媒体类型。例如,GIF 的媒体类型是 image/gif,JPEG 的媒体类型是 image/jpeg。为了确定文件的媒体类型,Web 服务器通常会查看文件的扩展名,将一个扩展名映射到另一个扩展名。
See developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types for common types.
常见类型请参见 developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types。
In a file called extensions.py, implement a program that prompts the user for the name of a file and then outputs that file’s media type if the file’s name ends, case-insensitively, in any of these suffixes:
在名为 extensions.py 的文件中,实现一个程序,该程序提示用户输入文件名,然后在文件名以以下任何后缀结尾时输出该文件的媒体类型,不区分大小写:
.gif.jpg.jpeg.png.pdf.txt.zip
If the file’s name ends with some other suffix or has no suffix at all, output application/octet-stream instead, which is a common default.
如果文件名以其他后缀结尾或根本没有后缀,则输出 application/octet-stream,这是常见的默认值。
Submit:
file = input("File name: ").lower().strip()
ext = file.split(".")[-1]
match ext:
case "gif":
print("image/gif")
case "jpg":
print("image/jpeg")
case "jpeg":
print("image/jpeg")
case "png":
print("image/png")
case "pdf":
print("application/pdf")
case "txt":
print("text/plain")
case "zip":
print("application/zip")
case _:
print("application/octet-stream")
Math Interpreter
Problem:
Python already supports math, whereby you can write code to add, subtract, multiply, or divide values and even variables. But let’s write a program that enables users to do math, even without knowing Python.
Python 已经支持数学, 您可以编写代码来加、减、乘或除值甚至变量。但是让我们编写一个程序,使用户能够进行数学运算,即使不懂 Python。
In a file called interpreter.py, implement a program that prompts the user for an arithmetic expression and then calculates and outputs the result as a floating-point value formatted to one decimal place. Assume that the user’s input will be formatted as x y z, with one space between x and y and one space between y and z, wherein:
在名为 interpreter.py 的文件中,实现一个程序,该程序提示用户输入算术表达式,然后计算结果并将其输出为格式化为小数点后一位的浮点值。假设用户的输入将格式化为 x y z,x 和 y 之间有一个空格,y 和 z 之间有一个空格,其中:
xis an integerx是一个整数yis+,-,*, or/y是+、-、*或/zis an integerz是一个整数
For instance, if the user inputs 1 + 1, your program should output 2.0. Assume that, if y is /, then z will not be 0.
例如,如果用户输入 1 + 1,则程序应输出 2.0。假设,如果 y 是 /,则 z 将不是 0。
Note that, just as python itself is an interpreter for Python, so will your interpreter.py be an interpreter for math!
请注意,正如 python 本身是 Python 的解释器一样,您的 interpreter.py 也会成为数学的解释器!
Submit:
arithmetic = input("Expression: ")
x = int(arithmetic.split(" ")[0])
y = arithmetic.split(" ")[1]
z = int(arithmetic.split(" ")[-1])
match y:
case "+":
print(f"{x + z:.1f}")
case "-":
print(f"{x - z:.1f}")
case "*":
print(f"{x * z:.1f}")
case "/":
print(f"{x / z:.1f}")
Meal Time
Problem:
Suppose that you’re in a country where it’s customary to eat breakfast between 7:00 and 8:00, lunch between 12:00 and 13:00, and dinner between 18:00 and 19:00. Wouldn’t it be nice if you had a program that could tell you what to eat when?
假设您所在的国家/地区习惯在 7:00 至 8:00 之间吃早餐,在 12:00 至 13:00 之间吃午餐,在 18:00 至 19:00 之间吃晚餐。如果你有一个程序可以告诉你什么时候吃什么不是很好吗?
In meal.py, implement a program that prompts the user for a time and outputs whether it’s breakfast time, lunch time, or dinner time. If it’s not time for a meal, don’t output anything at all. Assume that the user’s input will be formatted in 24-hour time as #:## or ##:##. And assume that each meal’s time range is inclusive. For instance, whether it’s 7:00, 7:01, 7:59, or 8:00, or anytime in between, it’s time for breakfast.
在 meal.py 中,实现一个程序,提示用户一段时间并输出是早餐时间 、 午餐时间还是晚餐时间 。如果不是吃饭的时间,就什么都不要输出。假设用户的输入将在 24 小时内格式化为 #:## 或 ##:##。并假设每顿饭的时间范围是包容性的。例如,无论是 7:00、7:01、7:59 还是 8:00,还是介于两者之间的任何时间,都是吃早餐的时间。
Structure your program per the below, wherein convert is a function (that can be called by main) that converts time, a str in 24-hour format, to the corresponding number of hours as a float. For instance, given a time like "7:30" (i.e., 7 hours and 30 minutes), convert should return 7.5 (i.e., 7.5 hours).
按照以下方式构建您的程序,其中 convert 是一个函数(可以由 main 调用),它将时间 (24 小时格式的 str)转换为相应的浮点数小时数。例如,给定像 “7:30” 这样的时间 (即 7 小时 30 分钟),convert 应该返回 7.5(即 7.5 小时)。
def main():
...
def convert(time):
...
if __name__ == "__main__":
main()
Submit:
def main():
now = convert(input("What time is it? "))
if 7 <= now <= 8:
print("breakfast time")
elif 12 <= now <= 13:
print("lunch time")
elif 18 <= now <= 19:
print("dinner time")
def convert(time):
h = float(time.split(":")[0])
m = float(time.split(":")[-1]) / 60
return h + m
if __name__ == "__main__":
main()
Challenge
If up for a challenge, optionally add support for 12-hour times, allowing the user to input times in these formats too:
如果需要挑战,可以选择添加对 12 小时时间的支持,允许用户也以以下格式输入时间:
#:## a.m.and##:## a.m.#:## 上午和##:## 上午#:## p.m.and##:## p.m.#:## 下午和##:## 下午
Submit:
def main():
now = convert(input("What time is it? "))
if 7 <= now <= 8:
print("breakfast time")
elif 12 <= now <= 13:
print("lunch time")
elif 18 <= now <= 19:
print("dinner time")
def convert(time):
time_T = time.replace("a.m.", "").replace("p.m.", "").strip()
h, m = time_T.split(":")
h = float(h)
m = float(m) / 60
if "p.m." in time and h != 12:
h += 12
elif "a.m." in time and h == 12:
h = 0
return h + m
if __name__ == "__main__":
main()

