python头歌练习五

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)
### 头歌平台上爬虫实战项目的解析 对于头歌平台上的爬虫实战项目,理解其核心在于如何利用自动化工具获取特定结构化数据。在设计此类应用时,通常会采用Selenium等库来模拟浏览器行为并交互操作网页元素[^2]。 #### 使用Selenium实现自动答题脚本的关键技术点 为了完成这类任务,可以构建一个基于Python的解决方案框架: 1. **初始化环境** 安装必要的依赖包,如`selenium`以及对应的WebDriver驱动程序。 ```bash pip install selenium ``` 2. **加载目标网站** 打开指定URL地址指向的目标在线测试页面,并保持会话连接状态以便后续操作。 ```python from selenium import webdriver driver = webdriver.Chrome() # 或者其他支持的浏览器实例 url = "https://example.com/exam" driver.get(url) ``` 3. **定位题目选项** 利用XPath或其他选择器语法精确定位到每一个试题及其备选答案区域内的HTML节点对象。 ```python questions_elements = driver.find_elements_by_xpath("//div[@class='question']") for q_element in questions_elements: question_text = q_element.text.strip() options_elements = q_element.find_elements_by_tag_name('input') for o_element in options_elements: option_value = o_element.get_attribute("value").strip() # 进一步处理逻辑... ``` 4. **匹配答案ID** 根据观察所得模式提取出隐藏于页面中的唯一标识符——即所谓的“答案id”,并已知正确解答数据库对照关联起来。 ```python answer_id_pattern = r"data-answer-id=\"(\d+)\"" import re def extract_answer_ids(html_content): matches = re.findall(answer_id_pattern, html_content) return {match: get_correct_answer(match) for match in matches} correct_answers_dict = extract_answer_ids(driver.page_source) ``` 5. **提交最终结果** 将计算得出的最佳猜测填入相应输入框内或触发单击事件确认作答动作直至全部完成为止。 ```python for answer_id, correct_option in correct_answers_dict.items(): target_input_field = driver.find_element_by_css_selector(f"[data-answer-id='{answer_id}'] ~ input[value='{correct_option}']") if target_input_field.is_displayed(): target_input_field.click() submit_button = driver.find_element_by_class_name('submit-button').click() ``` 上述方法展示了怎样运用编程技巧解决实际问题的过程;然而值得注意的是,在实施任何类型的Web Scraping活动之前,请务必仔细阅读服务条款并遵循合法合规的原则行事。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

南宫真汀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值