# 编写程序完成以下任务:
 # 1. 创建两个变量分别存储你的身高(米)和体重(公斤)
 # 2. 计算BMI指数(体重除以身高的平方)
 # 3. 打印出结果,保留两位小数 

def save_va(a,b):
    bmi = b//a**2
    return bmi

# 编写程序完成以下任务:
# 1. 让用户输入一个整数
# 2. 判断这个数是否能同时被3和5整除
# 3. 如果能,打印"FizzBuzz"
# 4. 如果只能被3整除,打印"Fizz"
# 5. 如果只能被5整除,打印"Buzz"
# 6. 如果都不能整除,打印这个数字

def is_is(number=None):
    number = int(input('pls input a number'))
    if number % 3==0 and number%5==0:
        return "FizzBuzz"
    elif number % 3==0:
        return "Fizz"
    elif number % 5==0:
        return "Buzz"
    else:
        return number

# 编写程序完成以下任务:
# 1. 使用for循环打印出1到20之间的所有偶数
# 2. 每行打印一个数字
# 3. 同时显示这个数字是2的几次方(如果是的话)


def is_tow(n):
    if n>0 and (n&(n-1))==0:
        cont = 0
        while n> 1:
            n>>=1
            cont += 1
        return cont
    else:
        return None


def get_two():
    for i in range(21):
        if i % 2== 0:
            has = is_tow(i)
            print(i,has)
        else:
            print(i)


# 编写程序完成以下任务:
# 1. 创建一个包含5个水果名称的列表
# 2. 让用户输入一个水果名称
# 3. 检查这个水果是否在列表中
# 4. 如果在,打印出它的位置(索引)
# 5. 如果不在,把它添加到列表末尾


def list_opertion():
    a = ['apple','bananna','orgrin','some','he']
    fruit = input('input a fruit')
    if fruit in a:
        return a.index(fruit)
    else:
        a.append(fruit)
    return a

# 编写程序完成以下任务:
# 1. 让用户输入一个句子
# 2. 统计这个句子中有多少个单词
# 3. 找出最长的单词
# 4. 把句子中的所有单词首字母大写后打印出来

def str_operation():
    str_str= input('pls input ')
    str_list = str_str.split(' ')
    howmany = len(str_list)
    max_len = sorted(str_list,key=lambda x:len(x))
    title = str_str.title().split(' ')
    title_list = [i[0] for i in title]
    return howmany,max_len[-1],title_list

# 使用json库完成以下任务:
# 1. 创建一个包含学生信息的字典,包括:
#    - 姓名
#    - 年龄
#    - 课程列表(每门课程包含名称和分数)
# 2. 将这个字典保存为JSON文件
# 3. 从文件读取JSON数据
# 4. 计算每个学生的平均分并添加到数据中
# 5. 将更新后的数据重新保存到文件
import json
def json_operation():
    dict_dict = {'name':'rain','age':18,'class':[{'class_name':'china','score':18}]}
    with open('json_file.json','w') as f:
        f.write(json.dumps(dict_dict))
    with open('json_file.json','r') as f:
        result = f.read() 
    result =json.loads(result)
    return result
# 使用os和sys库完成以下任务:
# 1. 在当前目录下创建一个名为'backup'的文件夹
# 2. 遍历当前目录下所有的.txt文件
# 3. 将这些文件复制到backup文件夹中
# 4. 在复制时,给文件名添加当前日期作为前缀
# 5. 打印出所有处理过的文件的详细信息(大小、创建时间等)

# import sys
# import os 
# import shutil
# import datetime

# def os_sys_operation():
#     if os.path.exists(os.path.join(os.path.dirname(__file__),'backup')):
#         base_dir_dir = os.makedirs(os.path.join(os.path.dirname(__file__),'backup'))
#     base_dir_dir = os.path.join(os.path.dirname(__file__),'backup')
#     dir_list = os.listdir(os.path.dirname(__file__))
#     for i in dir_list:
#         if i.endswith('.txt'):
#             datetime_file = f"{datetime.datetime.ctime}"+os.path.split(i)[-1]
#             shutil.copy(i,base_dir_dir)
#             print(os.path.getsize(i))


import os
import shutil
import datetime

def os_sys_operation():
    # 获取当前脚本所在目录
    current_dir = os.path.dirname(__file__)

    # 定义备份目录路径
    backup_dir = os.path.join(current_dir, 'backup')

    # 创建备份目录(如果不存在)
    os.makedirs(backup_dir, exist_ok=True)

    # 列出当前目录下所有文件
    for filename in os.listdir(current_dir):
        # 只处理.txt文件
        if filename.endswith('.txt'):
            # 构造完整文件路径
            src_file = os.path.join(current_dir, filename)

            # 生成带时间戳的新文件名
            timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
            new_filename = f"{timestamp}_{filename}"
            dst_file = os.path.join(backup_dir, new_filename)

            # 复制文件
            shutil.copy2(src_file, dst_file)

            # 打印文件大小(字节)
            print(f"文件 {filename} 大小: {os.path.getsize(src_file)} 字节")


# 使用collections库完成以下任务:
# 1. 给定一个长文本字符串
# 2. 使用Counter统计每个单词出现的次数
# 3. 找出出现最频繁的前5个单词
# 4. 使用defaultdict整理单词,按照单词长度分组
# 5. 打印每个长度对应的所有单词


from collections import defaultdict,Counter
import re

def process_text(text):
    words_list = re.findall(r'\b\w+\b',text.lower())
    counter_nnumber = Counter(words_list)

    top_5_words = counter_nnumber.most_common(5)
    print(top_5_words)
    print("出现最频繁的前5个单词:")
    for word, count in top_5_words:
        print(f"{word}: {count}次")
    set_list = defaultdict(list)
    for i in words_list:
        set_list[len(i)].append(i)
    for length in sorted(set_list):
        print(f'{length}:{", ".join(sorted(set_list[length]))}')

# 使用itertools库完成以下任务:
# 1. 给定一个列表[1,2,3,4,5]
# 2. 使用combinations生成所有可能的3个数字的组合
# 3. 使用permutations生成所有可能的3个数字的排列
# 4. 使用cycle创建一个循环迭代器,循环打印列表元素5次
# 5. 使用chain将多个列表合并成一个迭代器


from itertools import combinations, permutations, cycle, chain
def iter_process(list_list):
    target_list = list_list
    print('3个数字的组合:\n')
    for i in combinations(target_list,3):
        print(i)
    print('个数字的排列:\n')
    for i in permutations(target_list,3):
        print(i)
    counter = 0
    for i in cycle(target_list):
        print(i,'\n')
        counter+=1
        if counter>5*len(target_list):
            break


import hashlib
import os
class Userinfo(object):
    def __init__(self):
        self.datafile = 'Database.txt'
        self.choice_type()
        pass
    def choice_type(self):
        print("\n===== 用户系统 =====")
        print("1. 注册")
        print("2. 登录")
        print("3. 退出")
        self.choice = input("请选择操作: ").strip()
        self.username = input("请输入用户名: ").strip()
        self.password = input("请输入密码: ").strip()
        if choice == '1':
            self.register()
        elif choice == '2':
            self.login()
        elif choice == '3':
            print("再见!")

        else:
            print("无效输入,请重试!")
    def is_exised(self):
        if not os.path.exists(self.datafile):
            with open(self.datafile,'w'):pass
    def login(self):
        name = self.username
        password = self.password
        has_password = hashlib.sha256(password.encode('utf-8')).hexdigest()
        with open(self.datafile,'r') as f:
            data = f.readlines()
        for i in data:
            info = i.split(":")
            if info[0] == name and has_password == info[1]:
                print('login success')
    def register(self):
        name = self.username
        password = self.password
        has_password = hashlib.sha256(password.encode('utf-8')).hexdigest()
        with open(self.datafile,'w') as f:
            f.write(f"{name}:{has_password}\n")

        return True

    def has_password(self):
        return hashlib.sha256(self.password.encode('utf-8')).hexdigest()
    def is_user_exised(self):
        with open(self.datafile,'r') as f:
            data = f.readlines()
        for i in data:
            info = i.strip().split(':')
            if self.name == info[0] and self.password == info[1]:
                print('has user')
                return True
    def verify_credentials(self,username, password):
        pass

# 创建一个计时器的上下文管理器:
# 1. 实现一个Timer类,使用with语句计算代码块执行时间
# 2. 要求实现__enter__和__exit__方法
# 3. 在进入时记录开始时间,退出时计算执行时间
# 4. 支持将执行时间写入日志文件
# 5. 使用示例:
# with Timer(log_file='timing.log') as timer:
#     # 这里放要计时的代码
#     time.sleep(1)
import time 
from datetime import datetime

class Timer:
    def __init__(self,log_file=None):
        self.start_tiem = None
        self.log_file = log_file
        self.end_time = None
        self.elapsed = None
    def __enter__(self):
        self.start_tiem = time.perf_counter()
        return self
    def __exit__(self,exc_type, exc_val, exc_tb):
        self.end_time = time.perf_counter()
        self.elapsed = self.start_tiem - self.end_time
        if self.log_file:self.write_log()
        return None
    def write_log(self):
        log_format = (
            f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] "
            f"Execution time: {self.elapsed:.6f} seconds\n"
        )
        with open('log.log','w') as f:
            f.write(log_format)

    def get_elapsed(self):
        if self.elapsed is None:
            raise RuntimeError('error')

        return self.elapsed


# 实现一个数据流处理生成器:
# 1. 创建一个生成器函数,用于处理大文件
# 2. 每次读取一行数据,进行处理后yield
# 3. 实现过滤功能(跳过注释行和空行)
# 4. 实现数据转换功能(将每行数据转为字典)
# 5. 使用yield from优化生成器链
# 示例用法:
def process_log_file(log_file):
    yield from main_filter(
        filter_line(
            filter_line_data(log_file)
        )
    )
def filter_line_data(file_path):
    with open(file_path,'r',encoding='utf-8') as f:
        for line in f:
            yield line.rstrip('\n')
def filter_line(lines):
    for line in lines:
        strlines = line.strip()
        if strlines  and  not strlines.startswith('#'):
            yield strlines

def main_filter(lines):
    for line in lines:
        yield dict(
            item.split('=')
            for item in line.split(',')
            if '=' in item
        )


# 实现以下装饰器:
# 1. 创建一个retry装饰器,在函数失败时自动重试
# 2. 支持指定最大重试次数和重试间隔
# 3. 支持指定哪些异常需要重试
# 4. 记录每次重试的信息
# 5. 装饰器要支持带参数和不带参数两种方式
# 使用示例:
# @retry(max_attempts=3, delay=1)
# def unstable_function():
#     pass
from typing import Union,Callable,Tuple,Optional,Type
import functools
def retry(
    max_attempts:int =3,
    delay:Union[int,float]=1,
    exceptions: Union[Type[Exception], Tuple[Type[Exception], ...]] = Exception,
):
    def decorator(func: Callable):
        @functools.wraps(func)
        def wrapper(*args,**kwargs):
            last_exception = None
            for i in range(1,max_attempts+1):
                try:
                    return func(*args,**kwargs)
                except exceptions as e:
                    last_exception = e
                    print(f'retry {i}')
                    if i<max_attempts:
                        time.sleep(1)

            print('all retry is done')
            raise last_exception
        return wrapper
    if callable(max_attempts):  # 处理不带参数的情况
        func = max_attempts
        max_attempts = 3
        return decorator(func)
    return decorator





if __name__ =='__main__':
    # print(save_va(1.7,60))
    # print(is_is())
    # get_two()
    # print(list_opertion())
    # print(str_operation())
    # print(json_operation())
    #     text = """
    # Python is an interpreted, high-level and general-purpose programming language. 
    # Python's design philosophy emphasizes code readability with its notable use of 
    # significant whitespace. Its language constructs and object-oriented approach 
    # aim to help programmers write clear, logical code for small and large-scale projects.
    # """
    # process_text(text)
    # list_list = [1,2,3,4,5]
    # iter_process(list_list=list_list)
    # with Timer() as timer:
    #     time.sleep(1)
    # print(f"执行时间: {timer.get_elapsed():.3f}秒")
    # for record in process_log_file('large_file.log'):
#     print(record)
    # for record in process_log_file('log.log'):
    #     print(record)
    # @retry(3,1,exceptions=(ValueError, ZeroDivisionError))
    # def div_div(a,b):
    #     c = a/b

    #     return c
    # div_div(10,0)
    @retry
    def unstable_function():
        import random
        if random.random() < 0.7:
            raise ConnectionError("随机失败")
        return "成功"
    unstable_function()