1.Abstraction of objects and classes
1.1the_student_class
class Student:
def __init__(self, name, number):
self.name = name
self.scores = [0] * number
def getName(self):
return self.name
def getScore(self, i):
if 1 <= i <= len(self.scores):
return self.scores[i - 1]
else:
raise IndexError("Index out of range")
def setScore(self, i, score):
if 1 <= i <= len(self.scores):
self.scores[i - 1] = score
else:
raise IndexError("Index out of range")
def getAverage(self):
return sum(self.scores) / len(self.scores)
def getHighScore(self):
return max(self.scores)
def __str__(self):
score_str = " ".join(str(score) for score in self.scores)
return f"Name: {self.name}\nScores: {score_str}"
1.2library_borrow_system
class Book:
def __init__(self, title, author, year):
self.title = title
self.author = author
self.year = year
self.status = "Available" # 将初始状态改为 "Available",与测试用例输出更匹配
def check_out(self):
if self.status == "Checked out ":
print(f'"{self.title}" is already checked out.')
else:
self.status = "Checked out "
print(f'"{self.title}" has been checked out.')
def return_book(self):
if self.status == "Available":
print(f'"{self.title}" was not checked out.')
else:
self.status = "Available"
print(f'"{self.title}" has been returned.')
class Library:
def __init__(self):
self.books = []
def add_book(self, book):
self.books.append(book)
def list_books(self):
for book in self.books:
print(f'"{book.title}" by {book.author} ({book.year}) - {book.status}')
2.function
2.1anagram_checker
def prompt_get_strings():
print('Enter two strings and I\'ll tell you if they are anagrams: ')
def get_first_string():
while True:
first_string = input('Enter the first string: ')
cleaned_first_string = ''.join(char.lower() for char in first_string if char.isalpha())
if cleaned_first_string and len(cleaned_first_string) > 1:
return cleaned_first_string
else:
print('A valid input is required')
def get_second_string():
while True:
second_string = input('Enter the second string: ')
cleaned_second_string = ''.join(char.lower() for char in second_string if char.isalpha())
if cleaned_second_string and len(cleaned_second_string) > 1:
return cleaned_second_string
else:
print('A valid input is required')
def is_anagram(first_string, second_string):
sorted_first = sorted(first_string)
sorted_second = sorted(second_string)
return sorted_first == sorted_second
def print_is_anagram(first_string, second_string):
if is_anagram(first_string, second_string):
print(f'{first_string} and {second_string} are anagrams.')
else:
print(f'{first_string} and {second_string} are not anagrams.')
if __name__ == "__main__":
prompt_get_strings()
first_string = get_first_string()
second_string = get_second_string()
print_is_anagram(first_string, second_string)
2.2pay_off_credit_card
import math
# 获取有效的信用卡偿还余额函数
def get_balance():
while True:
try:
balance = int(input('What is your loan balance? '))
return balance
except ValueError:
print('A valid input is required')
# 获取有效的年利率 APR 函数,APR 必须为整数
def get_apr():
while True:
try:
apr = int(input('What is the APR on the loan (as a percent)? '))
return apr
except ValueError:
print('A valid input is required')
# 获取有效的月偿还额整数函数
def get_monthly_payments():
while True:
try:
monthly_payment = int(input('What are the monthly payment you can make? '))
return monthly_payment
except ValueError:
print('A valid input is required')
# 计算还清需要月份数函数
def calculate_months_until_paid_off(balance, apr, monthly_payment):
daily_rate = apr / 100 / 365
monthly_rate = (1 + daily_rate)**30 - 1
n = -1 * math.log(1 - balance * monthly_rate / monthly_payment) / math.log(1 + monthly_rate)
return math.ceil(n)
# 打印还清需要月份信息函数
def print_months_take_to_pay(months):
print(f'It will take you {months} months to pay off this loan')
if __name__ == "__main__":
balance = get_balance()
apr = get_apr()
monthly_payment = get_monthly_payments()
months_until_paid_off = calculate_months_until_paid_off(balance, apr, monthly_payment)
print_months_take_to_pay(months_until_paid_off)
2.3password_strength_indicator
# 导入正则库
import re
# 定义获取有效密码的函数,输入密码长度不小于1
def get_password():
while True:
password = input('Enter password: ')
if len(password) >= 1: # 补充代码判定输入密码长度不小于1
return password
else:
print('The password length must be at least 1.')
# 定义判断密码强度等级并打印输出判断结果的函数
def password_validator(password):
# 定义包含不同字符类别的标识
has_lower = re.search(r'[a-z]', password) is not None # 含小写字母
has_upper = re.search(r'[A-Z]', password) is not None # 含大写字母
has_digit = re.search(r'[0-9]', password) is not None # 含数字
has_special = re.search(r'[!@#$%^&*(),.?":{}|<>]', password) is not None # 这些是特殊字符
if len(password) <8 and password.isdigit():# 补充代码实现8位以下全数字是非常弱密码的判断条件
print(f'The password \'{password}\' is a very weak password')
elif len(password) < 8 and not password.isdigit(): # 补充代码实现8位以下有数字外字符是弱密码的判断条件
print(f'The password \'{password}\' is a weak password')
elif len(password) >= 8 and has_digit and (has_lower or has_upper) and not has_special:
# 补充代码实现不少于8位含字母、数字,不含特殊字符是强密码的判断条件
print(f'The password \'{password}\' is a strong password')
elif len(password) >= 8 and has_digit and (has_lower or has_upper) and has_special:
# 补充代码实现不少于8位含字母、数字、特殊字符是非常强密码的判断条件
print(f'The password \'{password}\' is a very strong password')
else:
print("Unable to determine the strength level")
if __name__ == "__main__":
password = get_password()
password_validator(password)