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])
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/549116.html
標籤:Python
上一篇:存盤引擎和資料型別
下一篇:java筆記(6) 抽象類和介面
