Week 5 Unit Tests
Testing my twittr
题目描述:
测试Problem Set2中Setting up my twttr程序;
题解:
twttr.py
def main():
print("Output: ", shorten(input("Input: ")))
def shorten(word):
ans = ""
for i in word:
if i.lower() not in ['a', 'e', 'i', 'o', 'u']:
ans+=i
return ans
if __name__ == "__main__":
main()
test_twttr.py
from twttr import shorten
def test_shorten():
assert shorten("aeiou") == ""
assert shorten("AEIOU") == ""
assert shorten("Twitter") == "Twttr"
assert shorten("What's your name?") == "Wht's yr nm?"
assert shorten("CS50") == "CS50"
Back to the Bank
题解:
bank.py
def main():
str = value(input("Greeting: "))
print(f"${str}")
def value(greeting):
greeting = greeting.strip().lower()
if greeting.startswith("hello"):
return 0
elif greeting.startswith("h"):
return 20
else:
return 100
if __name__ == "__main__":
main()
test_bank.py
from bank import value
def test_bank():
assert value("Hello") == 0
assert value("Hello, Newman") == 0
assert value("How you doing?") == 20
assert value("What's happening?") == 100
Re-requesting a Vanity Plate
题解:
plates.py
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()
test_plates.py
from plates import is_valid
def test_plates():
assert is_valid("CS50") == True
assert is_valid("CS05") == False
assert is_valid("CS50P") == False
assert is_valid("PI3.14") == False
assert is_valid("H") == False
assert is_valid("123456") == False
assert is_valid("OUTATIME") == False
Refueling
题解:
fuel.py
def main():
print(gauge(convert(input("Fraction: "))))
def convert(fraction):
while True:
try:
x, y = map(int, fraction.split("/"))
if y == 0:
raise ZeroDivisionError
if x > y:
raise ValueError
return round(x / y * 100)
except (ValueError, ZeroDivisionError):
pass
def gauge(percentage):
if percentage <= 1:
return "E"
elif percentage >= 99:
return "F"
else:
return f"{percentage}%"
if __name__ == "__main__":
main()
test_fuel.py
from fuel import convert, gauge
import pytest
def test_convert():
assert convert("3/4") == 75
assert convert("0/100") == 0
assert convert("100/100") == 100
assert convert("99/100") == 99
with pytest.raises(ValueError):
convert("x/y")
with pytest.raises(ZeroDivisionError):
convert("1/0")
def test_gauge():
assert gauge(0) == "E"
assert gauge(1) == "E"
assert gauge(100) == "F"
assert gauge(99) == "F"
assert gauge(2) == "2%"
Week6 File I/O
Lines of Code
题目描述:
计算.py文件代码有多少行;
题解:
import sys
## 判断输入是否合法
if len(sys.argv) != 2 or not sys.argv[1].endswith(".py"):
sys.exit("Invalid arguments.")
## 读取文件
try:
with open(sys.argv[1]) as file:
sum = 0
## 排除注释
for line in file:
if line.strip() and not line.lstrip().startswith("#"):
sum += 1
## 输出结果
print(sum)
except FileNotFoundError:
sys.exit("File does not exist.")
Pizza Py
题解:
from tabulate import tabulate
import csv
import sys
## 判断输出是否合法
if len(sys.argv) != 2 or not sys.argv[1].endswith(".csv"):
sys.exit("Invalid arguments.")
## Note that the tabulate package comes with just one function, per pypi.org/project/tabulate. You can install the package with:
## pip install tabulate
try:
with open(sys.argv[1]) as file:
print(tabulate(csv.DictReader(file), headers="keys", tablefmt="grid"))
except FileNotFoundError:
sys.exit("File does not exist.")
Scourgify
题目描述:
题解:
import csv
import sys
## 判断输出合法性
if len(sys.argv) != 3 or not sys.argv[1].endswith(".csv"):
sys.exit("Invalid arguments.")
try:
with open(sys.argv[1]) as input, open(sys.argv[2], "w", newline="") as output:
reader = csv.DictReader(input)
writer = csv.DictWriter(output, fieldnames=["first", "last", "house"])
writer.writeheader()
for row in reader:
last_name, first_name = row["name"].strip().split(", ")
writer.writerow(
{"first": first_name, "last": last_name, "house": row["house"]}
)
except FileNotFoundError:
sys.exit("File does not exist.")
CS50 P-Shirt
题解:
from PIL import Image, ImageOps
import sys
if len(sys.argv) != 3:
sys.exit("Invalid arguments.")
input = sys.argv[1]
output = sys.argv[2]
types = (".jpg", ".jpeg", ".png")
if (
not input.endswith(types)
or not output.endswith(types)
or input.split(".")[1] != output.split(".")[1]
):
sys.exit("Invalid arguments.")
shirt = Image.open("shirt.png")
try:
with Image.open(input) as im:
im = ImageOps.fit(im, shirt.size)
im.paste(shirt, shirt)
im.save(output)
except FileNotFoundError:
sys.exit("File does not exist.")
标签:__,assert,return,CS50,Python,sys,实验,import,def
From: https://www.cnblogs.com/sinowind/p/17293723.html