CS50-Python实验0,1,2

发布时间 2023-04-04 17:27:38作者: 纸忽者耶

Week0 Functions

Indoor Voice

题目描述:

将输入的字符串转化为全部小写的字符串;

思路:

lower():转换字符串中所有大写字符为小写。

题解:

print(input().lower())

Playback Speed

题目描述:

将输入的字符串中间空格部分替换为“...”;

思路:

1.split() :通过指定分隔符对字符串进行切片,如果第二个参数 num 有指定值,则分割为 num+1 个子字符串。

str = "this is string example....wow!!!"
print (str.split( ))       # 以空格为分隔符
print (str.split('i',1))   # 以 i 为分隔符
print (str.split('w'))     # 以 w 为分隔符
['this', 'is', 'string', 'example....wow!!!']
['th', 's is string example....wow!!!']
['this is string example....', 'o', '!!!']

2.join() :用于将序列中的元素以指定的字符连接生成一个新的字符串

symbol = "-";
seq = ("a", "b", "c"); # 字符串序列
print symbol.join( seq );

a-b-c

题解:

print("...".join(input().split()))

Making Faces

题目描述:

将输入字符串中”:)“替换为”?“,”:(“替换为"?";

思路:

replace() :把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。

题解:

def main():
    print(convert(input()))

def convert(text):
    return text.replace(":)", "?").replace(":(", "?")

if __name__=="__main__":
    main()

Einstein

题目描述:

E=mc2

思路:

题解:

def compute(m, c=300000000):
    return m * c * c

print("E:", compute(int(input("m: "))))

Tip Calculator

题目描述:

输入字符串dollars,percent,转换为浮点数并计算最终值;

思路:

取字符串某个区间:名字[位数:位数]

题解:

def main():
    dollars = dollars_to_float(input("How much was the meal? "))
    percent = percent_to_float(input("What percentage would you like to tip? "))
    tip = dollars * percent
    print(f"Leave ${tip:.2f}")


def dollars_to_float(d):
   return float(d[1:])


def percent_to_float(p):
    return float(p[:-1])/100


if __name__=="__main__":
    main()

Week1 Conditionals

Deep Thought

题目描述:

判断输入字符串是否为42,forty two, forty-two(包括大小写),若是则输出Yes否则输出No;

思路:

题解:

s = input("What is the Answer to the Great Question of Life, the Universe, and Everything? ").strip().lower()

if s in ["42", "forty two", "forty-two"]:
    print("Yes")
else:
    print("No")

Home Federal Savings Bank

题目描述:

判断字符串前几位是否为“hello”或者“h”(但不是hello)或者其他情况;

思路:

startswith(): 判断前几位与参数是否相同。

题解:

str = input("Greeting: ").strip().lower()

if str.startswith("hello"):
    print("$0")
elif str.startswith("h"):
    print("$20")
else:
    print("$100")

File Extensions

题目描述:

判断输入字符串是什么类型并相应输出;

思路:

数组存储然后匹配

题解:

types = {
    "gif": "image/gif",
    "jpg": "image/jpeg",
    "jpeg": "image/jpeg",
    "png": "image/png",
    "pdf": "application/pdf",
    "txt": "text/plain",
    "zip": "application/zip",
}

s = input("File name: ").strip().lower().split(".")[-1]
print(types.get(s, "application/octet-stream"))

Math Interpreter

题目描述:

输入算术表达式并输出结果;

思路:

spilt分解提取,后依靠eval函数进行计算;

题解:

a , c, b = input("Expression: ").split()
a, b= int(a), int(b)

ans = eval(f"{a} {c} {b}")

print(f"{ans:.1f}")

Meal Time

题目描述:

输入时间判断时间段为什么时间;

思路:

hours, minutes = time.split(":")

题解:

def main():
    time = input("What time is it?")
    time = convert(time)

    if 7<=time<=8:
        print("breakfast time")
    elif 12<=time<=13:
        print("lunch time")
    elif 18<=time<=19:
        print("dinner time")

def convert(time):
    hours, minutes = time.split(":")
    hours, minutes = float(hours), float(minutes)/60
    return hours+minutes


if __name__ == "__main__":
    main()

Week2 Loops

camelCase

题目描述:

输入字符串将其改为驼峰型命名;

思路:

遍历字符串,若字母为大写字母则连接“_”

题解:

camel = input("camelCase: ").strip()

snake = "".join(["_" + ch.lower() if ch.isupper() else ch for ch in camel])
print("snake_case:", snake)

Coke Machine

题目描述:

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.

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.

思路:

模拟

题解:

due, inserted = 50, 0

while inserted < due:
    print("Amount Due:", due - inserted)
    coin = int(input("Insert Coin: "))
    if coin in [5, 10, 25]:
        inserted += coin

print("Change Owed:", inserted - due)

Just setting up my twttr

题目描述:

将输出字符串中“aeiou”(无论大小下)删除;

思路:

遍历字符串,重新拼接新的字符串

题解:

str = input("Input: ")
ans =""

for i in str:
    if i.lower() not in ['a', 'e', 'i', 'o', 'u']:
        ans+=i

print(f"Output: {ans}")

Vanity Plates

题目描述:

  • “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.”
  • “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’.”
  • “No periods, spaces, or punctuation marks are allowed.”

思路:

模拟;

题解:

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


def is_valid(s):
    if len(s) < 2 or len(s) > 6:
        return False
    if not s[0].isalpha() or not s[1].isalpha():
        return False
    if not all(ch.isalnum() for ch in s):
        return False

    flag = False
    for ch in s:
        if ch.isdigit():
            flag = True
        if ch.isalpha() and flag:
            return False

    for ch in s:
        if ch.isdigit():
            return ch != "0"

    return True


if __name__ == "__main__":
    main()

Nutrition Facts

题目描述:

给出水果名输出对应的卡路里;

思路:

查表;

题解:

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,
}

s = input("Item: ").lower()
if s in fruits:
    print("Calories:", fruits[s])