课程:CS50’s Introduction to Programming with Python
CS50 Python 2025 课程的问题集作业提交。主要提供一个本人的解题思路,仅供参考。
Fuel Gauge
Problem
Fuel gauges indicate, often with fractions, just how much fuel is in a tank. For instance 1/4 indicates that a tank is 25% full, 1/2 indicates that a tank is 50% full, and 3/4 indicates that a tank is 75% full.
燃油表通常以分数表示油箱内的燃油量。例如,1/4表示油箱已满25%,1/2表示油箱已满50%,3/4表示油箱油量为75%。
In a file called fuel.py, implement a program that prompts the user for a fraction, formatted as X/Y, wherein each of X and Y is a positive integer, and then outputs, as a percentage rounded to the nearest integer, how much fuel is in the tank. If, though, 1% or less remains, output E instead to indicate that the tank is essentially empty. And if 99% or more remains, output F instead to indicate that the tank is essentially full.
在一个名为 fuel.py 的文件中,实现一个程序,提示用户输入一个分数,格式为 X/Y,其中 X 和 Y 各为正整数,然后输出油箱内燃料的百分比,四舍五入至最接近的整数。如果剩余 1%或更少,则输出 E,表示油箱基本空了。如果剩余 99%或更多,则输出 F,表示油箱基本满。
If, though, X or Y is not an integer, X is greater than Y, or Y is 0, instead prompt the user again. (It is not necessary for Y to be 4.) Be sure to catch any exceptions like ValueError or ZeroDivisionError.
但如果 X 或 Y 不是整数,X 大于 Y,或 Y 是 0,则再次提示用户。(Y 不必是 4。)务必捕捉异常,如 ValueError 或 ZeroDivisionError。
Submit
def main():
while True:
try:
fraction = input("Fraction: ")
x_str, y_str = fraction.split("/")
x = int(x_str)
y = int(y_str)
if 0 <= x <= y:
fuel = round(x / y * 100)
if fuel <= 1:
print("E")
elif fuel >= 99:
print("F")
else:
print(f"{fuel}%")
break
except (ValueError, ZeroDivisionError):
pass
main()
Tips
int() 遇到带小数点的字符串会抛出 ValueError
示例:
int("1.5")
结果:
ValueError: invalid literal for int() with base 10: '1.5'
原因:
int()只能接受 纯整数格式的字符串(如"3","-5")"1.5"不是整数格式,因此会抛出 ValueError
Felipe’s Taqueria
Problem
One of the most popular places to eat in Harvard Square is Felipe’s Taqueria, which offers a menu of entrees, per the dict below, wherein the value of each key is a price in dollars:
哈佛广场最受欢迎的餐厅之一是 Felipe’s Taqueria,根据下面的规定 ,提供一系列主菜,每把钥匙的价值以美元计价:
{
"Baja Taco": 4.25,
"Burrito": 7.50,
"Bowl": 8.50,
"Nachos": 11.00,
"Quesadilla": 8.50,
"Super Burrito": 8.50,
"Super Quesadilla": 9.50,
"Taco": 3.00,
"Tortilla Salad": 8.00
}
In a file called taqueria.py, implement a program that enables a user to place an order, prompting them for items, one per line, until the user inputs control-d (which is a common way of ending one’s input to a program). After each inputted item, display the total cost of all items inputted thus far, prefixed with a dollar sign ($) and formatted to two decimal places. Treat the user’s input case insensitively. Ignore any input that isn’t an item. Assume that every item on the menu will be titlecased.
在一个名为 taqueria.py 的文件中,实现一个程序,允许用户下单,提示他们每行一个物品,直到用户输入 control-d(这是结束程序输入的常见方式)。每输入一项后,显示迄今为止所有输入物品的总费用,前置一个美元符号($),格式为小数点后两位。对用户输入大小写不敏感。忽略任何非物品的输入。假设菜单上的每一项都会有标题。
Submit
def main():
items = {
"baja taco": 4.25,
"burrito": 7.50,
"bowl": 8.50,
"nachos": 11.00,
"quesadilla": 8.50,
"super burrito": 8.50,
"super quesadilla": 9.50,
"taco": 3.00,
"tortilla salad": 8.00
}
total = 0
while True:
try:
item = input("Item: ").lower()
if item in items:
total += items[item]
print(f"Total: ${total:.2f}")
except EOFError:
print()
break
main()
Grocery List
Problem
Suppose that you’re in the habit of making a list of items you need from the grocery store.
假设你习惯列出从超市需要买的东西清单。
In a file called grocery.py, implement a program that prompts the user for items, one per line, until the user inputs control-d (which is a common way of ending one’s input to a program). Then output the user’s grocery list in all uppercase, sorted alphabetically by item, prefixing each line with the number of times the user inputted that item. No need to pluralize the items. Treat the user’s input case-insensitively.
在一个名为 grocery.py 的文件中,实现一个程序,每行提示用户输入一个项目,直到用户输入 control-d(这是结束程序输入的常见方式)。然后输出用户的购物清单,全部大写,按项目字母顺序排序,每行前加上用户输入该物品的次数。没必要把这些词复数化。处理用户输入case-insensitively.
Submit
def main():
groceries = {}
while True:
try:
item = input().upper()
if item in groceries:
groceries[item] += 1
else:
groceries[item] = 1
except EOFError:
print()
for k in sorted(groceries):
print(f"{groceries[k]} {k}")
break
main()
Outdated
Problem
In the United States, dates are typically formatted in month-day-year order (MM/DD/YYYY), otherwise known as middle-endian order, which is arguably bad design. Dates in that format can’t be easily sorted because the date’s year comes last instead of first. Try sorting, for instance, 2/2/1800, 3/3/1900, and 1/1/2000 chronologically in any program (e.g., a spreadsheet). Dates in that format are also ambiguous. Harvard was founded on September 8, 1636, but 9/8/1636 could also be interpreted as August 9, 1636!
在美国,日期通常按月-日-年顺序 (MM/DD/YYYY)格式化,也称为中间端序,这或许是设计不佳。这种格式的日期不容易排序,因为日期的年份排在最后而不是第一。比如,在任何程序(比如电子表格)中,尝试按时间顺序排序 2/2/1800、3/3/1/1 2000。该格式的日期也存在歧义。哈佛成立于 1636 年 9 月 8 日,但 9/8/1636 也可以被解读为 1636 年 8 月 9 日!
Fortunately, computers tend to use ISO 8601, an international standard that prescribes that dates should be formatted in year-month-day (YYYY-MM-DD) order, no matter the country, formatting years with four digits, months with two digits, and days with two digits, “padding” each with leading zeroes as needed.
幸运的是,计算机通常采用 ISO 8601,这是一项国际标准,规定无论国家,日期都应按年-月-日(YYYY-MM-DD)格式化,年用四位数,月份用两位数,日用两位数字,并根据需要“填充”每个日期的前置零。
In a file called outdated.py, implement a program that prompts the user for a date, anno Domini, in month-day-year order, formatted like 9/8/1636 or September 8, 1636, wherein the month in the latter might be any of the values in the list below:
在一个名为 outdated.py 的文件中,实现一个程序,提示用户按月-日-年顺序输入日期 anno Domini,格式如 1636 年 9 月 8 日或 1636 年 9 月 8 日,其中后者的月份可以是以下列表中的任何一个值:
[
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
]
Then output that same date in YYYY-MM-DD format. If the user’s input is not a valid date in either format, prompt the user again. Assume that every month has no more than 31 days; no need to validate whether a month has 28, 29, 30, or 31 days.
然后以 YYYY-MM-DD 格式输出同一日期。如果用户输入的日期在任一格式中都不有效,请再次提示该用户。假设每个月的天数不超过 31 天;无需验证一个月是 28 天、29 天、30 天还是 31 天。
Submit
def main():
months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
]
while True:
try:
date = input("Date: ")
if "/" in date:
month_str, day_str, year_str = date.split("/")
month = int(month_str)
day = int(day_str)
year = int(year_str)
else:
month_str, day_str, year_str = date.split(" ")
month = int(months.index(month_str) + 1)
if "," not in day_str:
continue
else:
day = int(day_str.replace(",", ""))
year = int(year_str)
if 1 <= day <= 31 and 1 <= month <= 12:
print(f"{year}-{month:02d}-{day:02d}")
break
else:
pass
except:
pass
main()

