CS50P Problem Set 2

课程:CS50’s Introduction to Programming with Python

CS50 Python 2025 课程的问题集作业提交。主要提供一个本人的解题思路,仅供参考。

camelCase

Problem:

Source: en.wikipedia.org/wiki/Camel_case
来源:en.wikipedia.org/wiki/Camel_case

In some languages, it’s common to use camel case (otherwise known as “mixed case”) for variables’ names when those names comprise multiple words, whereby the first letter of the first word is lowercase but the first letter of each subsequent word is uppercase. For instance, whereas a variable for a user’s name might be called name, a variable for a user’s first name might be called firstName, and a variable for a user’s preferred first name (e.g., nickname) might be called preferredFirstName.
在某些语言中,当变量名称包含多个单词时,通常使用驼峰命名法(也称为“混合大小写”)作为变量名称,其中第一个单词的第一个字母是小写的,但每个后续单词的第一个字母是大写的。例如,用户名的变量可能称为 name,而用户名字的变量可能称为 firstName,而用户首选名字(例如昵称)的变量可能称为 preferredFirstName

Python, by contrast, recommends snake case, whereby words are instead separated by underscores (_), with all letters in lowercase. For instance, those same variables would be called namefirst_name, and preferred_first_name, respectively, in Python.
相比之下,Python 建议使用蛇形大小写 ,其中单词用下划线 (_) 分隔,所有字母均为小写。例如,这些相同的变量在 Python 中分别称为 namefirst_name 和 preferred_first_name

In a file called camel.py, implement a program that prompts the user for the name of a variable in camel case and outputs the corresponding name in snake case. Assume that the user’s input will indeed be in camel case.
在名为 camel.py 的文件中,实现一个程序,该程序提示用户输入驼峰命名法的变量名称,并以蛇形命名法输出相应的名称。假设用户的输入确实是驼峰式大小写。

Submit:

camelCase = input("camelCase: ")
snake_case = ""

for i in camelCase:
    if i == i.lower():
        snake_case += i
    else:
        snake_case =  snake_case + '_' + i.lower()

print(f"snake_case: {snake_case}")

Coke Machine

problem:

Suppose that a machine sells bottles of Coca-Cola (Coke) for 50 cents and only accepts coins in these denominations: 25 cents, 10 cents, and 5 cents.
假设一台机器以 50 美分的价格出售瓶装可口可乐(可乐),并且只接受以下面额的硬币:25 美分、10 美分和 5 美分。

In a file called coke.py, implement a program that prompts the user to insert a coin, one at a time, each time informing the user of the amount due. Once the user has inputted at least 50 cents, output how many cents in change the user is owed. Assume that the user will only input integers, and ignore any integer that isn’t an accepted denomination.
在名为 coke.py 的文件中,实现一个程序,提示用户一次插入一个硬币,每次都通知用户应付金额。一旦用户输入了至少 50 美分,输出用户欠多少零钱。假设用户只输入整数,并忽略任何不接受面额的整数。

Submit:

Amount_Due = 50
print(f"Amount Due: {Amount_Due}")

while Amount_Due > 0:
    Insert_Coin = int(input("Insert Coin: "))
    if Insert_Coin == 25 or Insert_Coin == 10 or Insert_Coin == 5:
        Amount_Due -= Insert_Coin
        if Amount_Due > 0:
            print(f"Amount Due: {Amount_Due}")
    else:
        print(f"Amount Due: {Amount_Due}")

print(f"Change Owed: {abs(Amount_Due)}")

Just setting up my twttr

problem:

When texting or tweeting, it’s not uncommon to shorten words to save time or space, as by omitting vowels, much like Twitter was originally called twttr. In a file called twttr.py, implement a program that prompts the user for a str of text and then outputs that same text but with all vowels (A, E, I, O, and U) omitted, whether inputted in uppercase or lowercase.
发短信或发推文时,缩短单词以节省时间或空间的情况并不少见,例如省略元音,就像 Twitter 最初称为 twttr 一样。在名为 twttr.py 的文件中,实现一个程序,该程序提示用户输入文本 str,然后输出相同的文本,但省略所有元音(A、E、I、O 和 U),无论是以大写还是小写输入。

Submit:

in_put = input("Input: ")
out_put = ""

for i in in_put:
    if i.lower() != 'a' and i.lower() != 'e' and i.lower() != 'i' and i.lower() != 'o' and i.lower() != 'u':
        out_put += i

print(f"Output: {out_put}")

Vanity Plates

problem:

In Massachusetts, home to Harvard University, it’s possible to request a vanity license plate for your car, with your choice of letters and numbers instead of random ones. Among the requirements, though, are:
在哈佛大学所在的马萨诸塞州,可以为您的汽车索取一个虚荣车牌 ,您可以选择字母和数字,而不是随机的。不过,这些要求包括:

  • “All vanity plates must start with at least two letters.”
    “所有梳妆台必须至少以两个字母开头。”
  • “… vanity plates may contain a maximum of 6 characters (letters or numbers) and a minimum of 2 characters.”
    “…梳妆台最多可包含 6 个字符(字母或数字),最少可包含 2 个字符。
  • “Numbers cannot be used in the middle of a plate; they must come at the end. For example, AAA222 would be an acceptable … vanity plate; AAA22A would not be acceptable. The first number used cannot be a ‘0’.”
    “数字不能在盘子中间使用;它们必须在最后出现。例如,AAA222 将是一个可以接受的……梳妆台;AAA22A 是不可接受的。使用的第一个数字不能是’0’。
  • “No periods, spaces, or punctuation marks are allowed.”
    “不允许使用句点、空格或标点符号。”

In plates.py, implement a program that prompts the user for a vanity plate and then output Valid if meets all of the requirements or Invalid if it does not. Assume that any letters in the user’s input will be uppercase. Structure your program per the below, wherein is_valid returns True if s meets all requirements and False if it does not. Assume that s will be a str. You’re welcome to implement additional functions for is_valid to call (e.g., one function per requirement).
在 plates.py 中,实现一个程序,提示用户输入梳妆台,然后输出 Valid if 满足所有要求,如果不满足,则输出 Invalid。假设用户输入中的任何字母都是大写的。按照以下方式构建您的程序,其中如果 s 满足所有要求, 则 is_valid 返回 True,如果满足,则返回 False。假设 s 将是一个 str。欢迎你实现其他函数供 is_valid 调用(例如,每个需求一个函数)。

def main():
    plate = input("Plate: ")
    if is_valid(plate):
        print("Valid")
    else:
        print("Invalid")


def is_valid(s):
    ...


main()

Submit:

def main():
    plate = input("Plate: ")
    if is_valid(plate):
        print("Valid")
    else:
        print("Invalid")

def two_letters(s):
    return len(s) >= 2 and s[0].isupper() and s[1].isupper()

def plates_len(s):
    return 2 <= len(s) <= 6

def end_numbers(s):
    number_start = False

    for i in s:
        if i.isdigit():
            if not number_start:
                number_start = True
                if i == '0':
                    return False
        else:
            if number_start:
                return False
    return True

def no_periods_spaces_punctuation(s):
    for i in s:
        if not (i.isdigit() or i.isupper()):
            return False
    return True

def is_valid(s):
    if two_letters(s) and plates_len(s) and end_numbers(s) and no_periods_spaces_punctuation(s):
        return True
    else:
        return False

main()

Nutrition Facts

problem:

The U.S. Food & Drug Adminstration (FDA) offers downloadable/printable posters that “show nutrition information for the 20 most frequently consumed raw fruits … in the United States. Retail stores are welcome to download the posters, print, display and/or distribute them to consumers in close proximity to the relevant foods in the stores.”
美国食品和药物管理局 (FDA) 提供可下载/可打印的海报 ,“显示 20 种最常食用的生水果的营养信息……在美国。欢迎零售店户下载海报,印制、展示及/或派发给店内相关食品附近的消费者。」

In a file called nutrition.py, implement a program that prompts consumers users to input a fruit (case-insensitively) and then outputs the number of calories in one portion of that fruit, per the FDA’s poster for fruits, which is also available as text. Capitalization aside, assume that users will input fruits exactly as written in the poster (e.g., strawberries, not strawberry). Ignore any input that isn’t a fruit.
在一个名为 nutrition.py 的文件中,实施一个程序,提示消费者用户输入水果(不区分大小写),然后根据 FDA 的水果海报输出该水果的一部分的卡路里数量,该海报也以文本形式提供 。撇开大写不谈,假设用户会完全按照海报上所写的方式输入水果(例如, 草莓 ,而不是草莓 )。忽略任何不是水果的输入。

Submit:

fruits = {
    "apple": 130,
    "avocado": 50,
    "banana": 110,
    "cantaloupe": 50,
    "grapefruit": 60,
    "grapes": 90,
    "honeydew melon": 50,
    "kiwifruit": 90,
    "lemon": 15,
    "lime": 20,
    "Nectarine": 60,
    "orange": 80,
    "peach": 60,
    "pear": 100,
    "pineapple": 50,
    "plums": 70,
    "strawberries": 50,
    "sweet cherries": 100,
    "tangerine": 50,
    "watermelon": 80
}

item = input("Item: ")
for k in fruits:
    if item.lower() == k:
        print(f"Calories: {fruits[k]}")
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇