25级第五次实验报告

2025010089  1
2025010090  
2025010091  1
2025010092 1

 

2025010093  1
2025010094  1
2025010095  
2025010096  1
2025010097  
2025010098  1
2025010099  1
2025010100  
2025010101 1
2025010102

 1

2025010103
2025010104  1
2025010105  
2025010106  
2025010107
2025010108  
2025010109
2025010110  
2025010112  
2025010113  1
2025010114  1
2025010115  1
2025010117  1
2025010118  1
2025010119  1
2025010120  
2025010121  1
2025010122  1
2025010123  
2025010124  1
2025010125
2025010126  
2025010127  
2025010128  1
2025010130  1
2025010131
2025010132

2025010089张静文

定义函数求复数取模夹角

import math

# 定义复数求模和辐角函数
def complex_mod_arg(a, b):
    mod = math.sqrt(a**2 + b**2)       # 模长
    arg = math.atan2(b, a)             # 弧度夹角
    arg_deg = math.degrees(arg)        # 转为角度
    return mod, arg, arg_deg

# 测试
if __name__ == "__main__":
    real = 3
    imag = 4
    mo, ang_rad, ang_deg = complex_mod_arg(real, imag)
    print(f"模:{mo:.2f}")
    print(f"弧度:{ang_rad:.2f}")

屏幕截图 2026-06-02 002251

 2025010090殷慧湘

import numpy as np

def get_matrix_rank(mat):
    """
    调用numpy求矩阵的秩
    :param mat: 二维列表 / np.array
    :return: 矩阵的秩
    """
    arr = np.array(mat, dtype=float)
    return np.linalg.matrix_rank(arr)


# 测试示例
if __name__ == "__main__":
    A = [[1, 2, 3], [2, 4, 6], [1, 0, 1]]
    B = [[1, 2], [2, 4]]
    C = [[1, 2], [3, 4]]

    print("矩阵A秩:", get_matrix_rank(A))
    print("矩阵B秩:", get_matrix_rank(B))
    print("矩阵C秩:", get_matrix_rank(C))

  屏幕截图 2026-06-17 195347

 

2025010091张译心

 
# 订单管理系统 - 多角色权限版
import random
import time

# 存储用户账号、角色
user_list = {
    "admin": {"pwd": "123456", "role": "管理员"},
    "staff1": {"pwd": "654321", "role": "员工"},
    "user1": {"pwd": "111111", "role": "客户"}
}

# 订单数据 格式:{订单号: {客户, 商品, 单价, 数量, 总价, 状态}}
order_data = {}
current_user = None  # 当前登录用户


# 生成随机订单号
def create_order_id():
    return f"ORD{time.strftime('%Y%m%d')}{random.randint(1000, 9999)}"


# 登录功能
def login():
    global current_user
    print("===== 用户登录 =====")
    username = input("请输入账号:")
    pwd = input("请输入密码:")

    if username in user_list and user_list[username]["pwd"] == pwd:
        current_user = user_list[username]["role"]
        print(f"登录成功!当前身份:{current_user}\n")
        return True
    else:
        print("账号或密码错误!\n")
        return False


# 1. 新增订单(全员可用)
def add_order():
    oid = create_order_id()
    customer = input("客户姓名:")
    goods = input("商品名称:")
    price = float(input("商品单价:"))
    num = int(input("购买数量:"))
    total = price * num

    order_data[oid] = {
        "customer": customer,
        "goods": goods,
        "price": price,
        "num": num,
        "total": total,
        "status": "已下单"
    }
    print(f"订单创建成功,订单号:{oid}\n")


# 2. 查看所有订单(管理员/员工可用)
def show_all_order():
    if not order_data:
        print("暂无订单数据\n")
        return
    print("===== 全部订单列表 =====")
    for oid, info in order_data.items():
        print(f"订单号:{oid}")
        print(f"客户:{info['customer']}  商品:{info['goods']}")
        print(f"单价:{info['price']}  数量:{info['num']}  总价:{info['total']}")
        print(f"订单状态:{info['status']}\n")


# 3. 修改订单(仅管理员可用)
def modify_order():
    oid = input("请输入要修改的订单号:")
    if oid not in order_data:
        print("该订单不存在!\n")
        return

    print("1.修改商品  2.修改数量  3.修改订单状态")
    choice = input("请选择修改项:")
    order = order_data[oid]

    if choice == "1":
        order["goods"] = input("输入新商品名称:")
    elif choice == "2":
        new_num = int(input("输入新数量:"))
        order["num"] = new_num
        order["total"] = order["price"] * new_num
    elif choice == "3":
        order["status"] = input("输入新状态(已付款/已发货/已完成):")
    else:
        print("选择无效!")
        return
    print("订单修改成功!\n")


# 4. 删除订单(仅管理员可用)
def del_order():
    oid = input("请输入要删除的订单号:")
    if oid in order_data:
        del order_data[oid]
        print("订单已删除!\n")
    else:
        print("该订单不存在!\n")


# 5. 客户查询自己的订单(客户专属)
def customer_query():
    name = input("请输入你的姓名:")
    has_order = False
    print("===== 你的订单 =====")
    for oid, info in order_data.items():
        if info["customer"] == name:
            has_order = True
            print(f"订单号:{oid}  商品:{info['goods']}  总价:{info['total']}  状态:{info['status']}")
    if not has_order:
        print("未查询到你的订单")
    print()


# 功能菜单分发(权限控制核心)
def menu():
    while True:
        print("======== 订单系统菜单 ========")
        print("1. 新增订单")
        if current_user in ["管理员", "员工"]:
            print("2. 查看全部订单")
        if current_user == "管理员":
            print("3. 修改订单")
            print("4. 删除订单")
        if current_user == "客户":
            print("5. 查询我的订单")
        print("0. 退出系统")
        opt = input("请选择功能编号:")

        if opt == "0":
            print("已退出系统,再见!")
            break
        elif opt == "1":
            add_order()
        elif opt == "2" and current_user in ["管理员", "员工"]:
            show_all_order()
        elif opt == "3" and current_user == "管理员":
            modify_order()
        elif opt == "4" and current_user == "管理员":
            del_order()
        elif opt == "5" and current_user == "客户":
            customer_query()
        else:
            print("暂无权限或输入错误,请重新选择!\n")


# 程序入口
if __name__ == "__main__":
    if login():
        menu()

屏幕截图 2026-06-14 151948

 


 2025010092朱翔鸽

落叶

import tkinter as tk
import random

root = tk.Tk()
root.title("落叶飘落")
W, H = 800, 600
root.geometry(f"{W}x{H}")
cv = tk.Canvas(root, bg="#283328")
cv.pack(fill="both", expand=True)

leaves = []

class Leaf:
    def __init__(self):
        self.x = random.randint(0, W)
        self.y = random.randint(-H, 0)
        self.r = random.randint(4, 12)
        self.dy = random.uniform(1, 3)
        self.dx = random.uniform(-1.2, 1.2)
        self.col = random.choice(["#8B4513", "#CD853F", "#DEB887", "#A0522D"])
        self.id = cv.create_oval(self.x-self.r, self.y-self.r//2,
                                 self.x+self.r, self.y+self.r//2, fill=self.col, outline="")

for _ in range(150):
    leaves.append(Leaf())

def fall():
    for lf in leaves:
        lf.y += lf.dy
        lf.x += lf.dx
        cv.coords(lf.id, lf.x-lf.r, lf.y-lf.r//2, lf.x+lf.r, lf.y+lf.r//2)
        if lf.y > H:
            lf.x = random.randint(0, W)
            lf.y = random.randint(-50, 0)
    root.after(16, fall)

fall()
root.mainloop()

屏幕截图 2026-06-17 192321

 

 

2025010093惠盾

import subprocess
import sys

def connect_wifi_windows(ssid):
    """
    Windows 连接已知 WiFi
    :param ssid: WiFi 名称
    """
    try:
        # Windows 连接 WiFi 命令
        cmd = f'netsh wlan connect name="{ssid}"'
        result = subprocess.run(cmd, shell=True, capture_output=True, text=True, encoding='gbk')
        
        if result.returncode == 0:
            print(f"✅ 成功连接 WiFi:{ssid}")
        else:
            print(f"❌ 连接失败:{result.stderr}")
            
    except Exception as e:
        print(f"⚠️  错误:{str(e)}")

def get_available_wifi_windows():
    """查看附近可用 WiFi"""
    subprocess.run('netsh wlan show networks', shell=True)

if __name__ == "__main__":
    # 在这里修改成你的 WiFi 名称
    WIFI_NAME = ("AKU-WiFi")
    
    print("正在连接 WiFi...")
    connect_wifi_windows(WIFI_NAME)

屏幕截图 2026-06-03 111723

 

2025010094谢润泽

from docx import Document
from docx.shared import Pt, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.oxml.ns import qn

def force_change_title_format(doc_path, save_path):
    doc = Document(doc_path)

    # -------------------------- 1. 先把所有正文段落的格式重置为默认(避免之前格式残留) --------------------------
    for para in doc.paragraphs:
        # 先重置所有段落的基础格式
        para.alignment = WD_ALIGN_PARAGRAPH.LEFT
        para.paragraph_format.space_before = Pt(0)
        para.paragraph_format.space_after = Pt(0)
        para.paragraph_format.line_spacing = 1.5

        # 给所有文字统一设置默认字体(宋体,五号)
        for run in para.runs:
            run.font.name = "宋体"
            run._element.rPr.rFonts.set(qn("w:eastAsia"), "宋体")
            run.font.size = Pt(10.5)  # 五号字 = 10.5磅
            run.font.bold = False
            run.font.color.rgb = RGBColor(0, 0, 0)

    # -------------------------- 2. 精准修改指定段落的格式 --------------------------
    # 例:修改第1段(标题行),段落序号从0开始数
    # 比如你的文档第1行是「尊敬的老师、同学:」,它就是 doc.paragraphs[0]
    # 你可以根据自己的文档,修改下面的序号和格式
    if len(doc.paragraphs) >= 1:
        # 修改第0段(第1行):作为主标题
        title_para = doc.paragraphs[0]
        # 对齐方式:居中
        title_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
        # 段前、段后间距
        title_para.paragraph_format.space_before = Pt(12)
        title_para.paragraph_format.space_after = Pt(12)
        # 强制修改这段所有文字的格式
        for run in title_para.runs:
            run.font.name = "黑体"
            run._element.rPr.rFonts.set(qn("w:eastAsia"), "黑体")
            run.font.size = Pt(18)
            run.font.bold = True
            run.font.color.rgb = RGBColor(0, 0, 0)

    # 例:修改第2段(doc.paragraphs[1]),作为副标题
    # if len(doc.paragraphs) >= 2:
    #     sub_title = doc.paragraphs[1]
    #     sub_title.alignment = WD_ALIGN_PARAGRAPH.CENTER
    #     for run in sub_title.runs:
    #         run.font.name = "楷体"
    #         run._element.rPr.rFonts.set(qn("w:eastAsia"), "楷体")
    #         run.font.size = Pt(14)
    #         run.font.bold = False

    # 保存文档
    doc.save(save_path)
    print("✅ 格式强制修改完成!已保存到:", save_path)

if __name__ == "__main__":
    # 替换成你的文件路径
    original_file = "test.docx"
    output_file = "强制改格式后.docx"
    force_change_title_format(original_file, output_file)

屏幕截图 2026-06-02 221922

 

 

2025010096刘加鑫

import datetime

class MyDate:
    def __init__(self, year, month, day):
        """初始化日期对象"""
        # 用datetime.date做底层,保证日期合法性
        self._date = datetime.date(year, month, day)

    def __add__(self, days):
        """日期加法:加上指定天数,返回新的MyDate对象"""
        if not isinstance(days, int):
            raise TypeError("天数必须是整数")
        new_date = self._date + datetime.timedelta(days=days)
        return MyDate(new_date.year, new_date.month, new_date.day)

    def __sub__(self, other):
        """
        日期减法:
        1. 减去整数:返回往前推指定天数的新日期
        2. 减去另一个MyDate对象:返回两个日期相差的天数
        """
        if isinstance(other, int):
            new_date = self._date - datetime.timedelta(days=other)
            return MyDate(new_date.year, new_date.month, new_date.day)
        elif isinstance(other, MyDate):
            delta = self._date - other._date
            return delta.days
        else:
            raise TypeError("减法只支持整数天数或MyDate对象")

    def __str__(self):
        """打印日期格式:YYYY-MM-DD"""
        return f"{self._date.year:04d}-{self._date.month:02d}-{self._date.day:02d}"


# -------------------- 测试代码 --------------------
if __name__ == "__main__":
    # 1. 创建日期对象
    d1 = MyDate(2026, 5, 27)
    print("初始日期:", d1)

    # 2. 日期加法:加 10 天
    d2 = d1 + 10
    print("加 10 天后:", d2)

    # 3. 日期减法:减 5 天
    d3 = d1 - 5
    print("减 5 天后:", d3)

    # 4. 两个日期相减,计算相差天数
    diff = d2 - d3
    print(f"{d2} 与 {d3} 相差:{diff} 天")

屏幕截图 2026-06-02 223458

 

 

2025010097马浩

爬取豆瓣音乐评分榜前十

import requests
from bs4 import BeautifulSoup


def crawl_douban_music():
    url = "https://music.douban.com/top250"

    # 1. 超级伪装头:明确告诉服务器,不要给我压缩数据
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
        "Accept-Encoding": "identity"  # <--- 关键!这行代码禁止了压缩
    }

    print(f"正在请求:{url}")

    try:
        response = requests.get(url, headers=headers, timeout=10)

        # 2. 检查状态
        if response.status_code != 200:
            print(f"❌ 失败!状态码:{response.status_code}")
            return

        # 3. 强制设置编码(防止中文乱码)
        response.encoding = 'utf-8'

        # 【调试】打印前100个字符,确认是不是乱码
        # 如果你看到正常的 <html> 标签,说明成功了
        print(f"网页预览:{response.text[:100]}...")

        soup = BeautifulSoup(response.text, "html.parser")

        # 4. 豆瓣 Top250 的每一条记录都在 <tr class="item"> 里
        items = soup.find_all("tr", class_="item")

        if not items:
            print("❌ 依然没找到数据。请检查网络或稍后再试。")
            return

        print(f"✅ 成功找到 {len(items)} 条记录!正在提取前十名:\n")

        # 5. 提取前十名
        for i, item in enumerate(items[:10]):
            # 歌名在 <a> 标签里
            title_tag = item.find("a")
            title = title_tag["title"] if title_tag else "未知歌名"

            # 评分在 <span class="rating_nums"> 里
            rating_tag = item.find("span", class_="rating_nums")
            rating = rating_tag.text if rating_tag else "无评分"

            print(f"NO.{i + 1} 《{title}》 - 评分: {rating}")

    except Exception as e:
        print(f"❌ 程序出错:{e}")


if __name__ == "__main__":
    crawl_douban_music()

屏幕截图 2026-06-02 215304

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

2025010098韩晓媛

证件照背景颜色转换

import cv2,numpy as np
#获取证件照原图
img=cv2.imread(r"C:\Users\HXY\zczjz.jpg")
#获取图片尺寸,返回结果分别表示:高度、宽度、深度
h,w,d=img.shape
#根据原图尺寸生成新的背景色图
bg=np.zeros(img. shape,np.uint8)
#颜色格式为BGR,参考蓝色背景RGB(0,195,253)
bg[:]=[0,0,255]
#锁定原图中的人物区域
a=cv2.inRange(img,(0,0,0),(252,252,252))
figure=cv2.bitwise_and(img, img,mask=a)
#设置新背景区
b=cv2.bitwise_not(a)
bg=cv2.bitwise_and(bg,bg,mask=b)
#人物图与背景图融合
new=cv2. add(figure,bg)
#查看效果
cv2.imshow('red bg',new)
#保存最终图片
cv2.imwrite('new_zjz.jpg',new)

屏幕截图 2026-05-27 111419

 

2025010099张嘉诚

文档分段并保存

import os

# -------------------------- 配置区 --------------------------
input_file = "新时代中国特色社会主义.txt"    # 输入文档,和脚本放同一文件夹
output_folder = "分段结果"   # 自动生成的存放所有段落文件的文件夹
# -----------------------------------------------------------

def main():
    # 检查输入文件是否存在
    if not os.path.isfile(input_file):
        print(f"错误:未找到文件 {input_file}")
        return

    # 读取全文
    with open(input_file, "r", encoding="utf-8") as f:
        content = f.read()

    # 按空行拆分段落
    lines = [line.strip() for line in content.splitlines()]
    paragraphs = []
    current = []

    for line in lines:
        if line:
            current.append(line)
        else:
            if current:
                paragraphs.append(" ".join(current))
                current = []
    # 保存最后一段
    if current:
        paragraphs.append(" ".join(current))

    # 创建输出文件夹
    if not os.path.exists(output_folder):
        os.mkdir(output_folder)

    # 每段单独保存
    for index, para_text in enumerate(paragraphs, start=1):
        filename = f"第{index}段.txt"
        full_path = os.path.join(output_folder, filename)
        with open(full_path, "w", encoding="utf-8") as out_f:
            out_f.write(para_text)

    print(f"处理完成!一共 {len(paragraphs)} 个段落")
    print(f"所有文件保存在文件夹:{output_folder}")

if __name__ == "__main__":
    main()

屏幕截图 2026-06-14 222132

 2025010100霍延萌

归一化

import numpy as np

def normalize_xyz(xyz):
    # 向量归一:每个xyz除以自身模长
    length = np.sqrt(np.sum(xyz**2, axis=1, keepdims=True))
    length[length < 1e-7] = 1.0
    return xyz / length

# 示例矩阵:4行3列xyz
matrix = np.array([
    [1, 2, 3],
    [0, 0, 0],
    [4, 5, 6],
    [1, 1, 1]
], dtype=float)

normalized = normalize_xyz(matrix)

print("原始矩阵:")
print(matrix)
print("\n归一化后的单位向量:")
print(normalized)
print("\n各向量的模长(应全为1,零向量为0):")
print(np.linalg.norm(normalized, axis=1))

  屏幕截图 2026-06-17 190546

 

2025010101袁泉

三维椭球

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# 关键:设置支持中文的字体
plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei']
plt.rcParams['axes.unicode_minus'] = False  # 解决负号显示问题

# 创建画布与3D坐标系
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, projection='3d')

# 椭球参数:x,y,z轴半径
a, b, c = 3, 2, 1

# 生成球面角度参数
u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 100)
u, v = np.meshgrid(u, v)

# 椭球参数方程
x = a * np.cos(u) * np.sin(v)
y = b * np.sin(u) * np.sin(v)
z = c * np.cos(v)

# 绘制三维椭球
ax.plot_surface(x, y, z, cmap='coolwarm', alpha=0.7)

# 设置坐标轴标签(现在中文能正常显示了)
ax.set_xlabel('X 轴')
ax.set_ylabel('Y 轴')
ax.set_zlabel('Z 轴')
ax.set_title('三维椭球体')

plt.show()

屏幕截图 2026-05-24 162028

 

 

 2025010102 沈玉婷

取左函数

# 定义一个自己的函数:取字符串左边的n个字符
def quzuo(s, n):
    # 用Python的切片,从第0个字符开始,取到第n个位置(不包含n)
    jieguo = s[0:n]
    # 把结果返回出去
    return jieguo

# 测试一下
text = "ABC"
result = quzuo(text, 2)
print(result)

屏幕截图 2026-05-24 232214

 2025010103黄俊

计算函数

import numpy as np

# 1. 矩阵基础运算
def matrix_calc():
    print("======= 矩阵基础运算 =======")
    # 自定义两个矩阵,可随意改数值
    A = np.array([[1, 2],
                  [3, 4]])
    B = np.array([[5, 6],
                  [7, 8]])

    print("矩阵A:")
    print(A)
    print("矩阵B:")
    print(B)

    print("A + B:")
    print(A + B)
    print("A - B:")
    print(A - B)
    print("A * B(矩阵乘法):")
    print(A @ B)

    print("A行列式:", np.linalg.det(A))
    print("A逆矩阵:")
    print(np.linalg.inv(A))


# 2. 线性函数 y = Ax 变换
def linear_transform():
    print("\n======= 线性函数 y=Ax 变换 =======")
    # 线性变换矩阵
    trans_mat = np.array([[2, 0],
                          [0, 3]])
    # 原始向量x
    x = np.array([1, 2])
    # 线性变换结果 y = A·x
    y = trans_mat @ x
    print(f"变换矩阵:\n{trans_mat}")
    print(f"原始向量 x = {x}")
    print(f"线性变换结果 y = Ax = {y}")


# 3. 矩阵特征值、特征向量(特殊向量)
def eigen_vector():
    print("\n======= 特征值 & 特征向量 =======")
    mat = np.array([[2, 1],
                    [1, 2]])
    val, vec = np.linalg.eig(mat)
    print("原矩阵:")
    print(mat)
    print("特征值:", val)
    print("特征向量(按列):")
    print(vec)


if __name__ == "__main__":
    # 依次执行所有功能
    matrix_calc()
    linear_transform()
    eigen_vector()

屏幕截图 2026-06-02 214958

 2025010104许乐乐

# 输入向量
v1 = list(map(int, input("输入向量1(三个数空格分开):").split()))
v2 = list(map(int, input("输入向量2(三个数空格分开):").split()))

# 加法
add = [v1[0]+v2[0], v1[1]+v2[1], v1[2]+v2[2]]
# 减法
sub = [v1[0]-v2[0], v1[1]-v2[1], v1[2]-v2[2]]
# 点积
dot = v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2]
# 叉积 a×b
cx1 = v1[1]*v2[2] - v1[2]*v2[1]
cx2 = v1[2]*v2[0] - v1[0]*v2[2]
cx3 = v1[0]*v2[1] - v1[1]*v2[0]
cross = [cx1, cx2, cx3]

# 输出结果
print("向量相加:", add)
print("向量相减:", sub)
print("向量点积:", dot)
print("向量叉积:", cross)

image

 

 

2025010107孙瑞妍

转换为年月日

# 导入日期模块
import datetime

# 获取用户输入
year = int(input("请输入年份:"))
month = int(input("请输入月份:"))
day = int(input("请输入日期:"))

# 定义星期列表
week_list = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"]

# 计算并输出
date = datetime.date(year, month, day)
week = week_list[date.weekday()]
print(f"{year}年{month}月{day}日 是 {week}")

屏幕截图 2026-06-01 221500

 2025010109 黄帅豪

用类的方式求矩阵

class Matrix:
    # 构造方法:初始化矩阵,接收二维列表作为矩阵数据
    def __init__(self, data):
        # 存储矩阵原始二维数组
        self.data = data
        # 获取矩阵行数
        self.row_num = len(data)
        # 判断矩阵是否为空,再获取列数
        if self.row_num == 0:
            self.col_num = 0
        else:
            self.col_num = len(data[0])

    # 方法1:打印输出矩阵
    def print_matrix(self):
        for row in self.data:
            print(row)

    # 方法2:矩阵转置运算
    def transpose_matrix(self):
        # 存放转置后的矩阵
        trans_data = []
        # 遍历原矩阵每一列
        for col in range(self.col_num):
            new_row = []
            # 遍历原矩阵每一行
            for row in range(self.row_num):
                # 把原矩阵第row行第col列元素放入新行
                new_row.append(self.data[row][col])
            trans_data.append(new_row)
        # 返回新的矩阵对象
        return Matrix(trans_data)

    # 方法3:矩阵加法运算
    def add_matrix(self, other_mat):
        # 判断两个矩阵行列是否完全相同
        if self.row_num != other_mat.row_num or self.col_num != other_mat.col_num:
            raise ValueError("加法错误:两个矩阵行数、列数必须完全相等!")
        add_result = []
        # 双重循环遍历每个位置
        for r in range(self.row_num):
            temp_row = []
            for c in range(self.col_num):
                # 对应位置元素相加
                num = self.data[r][c] + other_mat.data[r][c]
                temp_row.append(num)
            add_result.append(temp_row)
        return Matrix(add_result)

    # 方法4:矩阵减法运算
    def sub_matrix(self, other_mat):
        if self.row_num != other_mat.row_num or self.col_num != other_mat.col_num:
            raise ValueError("减法错误:两个矩阵行数、列数必须完全相等!")
        sub_result = []
        for r in range(self.row_num):
            temp_row = []
            for c in range(self.col_num):
                num = self.data[r][c] - other_mat.data[r][c]
                temp_row.append(num)
            sub_result.append(temp_row)
        return Matrix(sub_result)

    # 方法5:矩阵乘法运算
    def mul_matrix(self, other_mat):
        # 矩阵相乘条件:左矩阵列数 = 右矩阵行数
        if self.col_num != other_mat.row_num:
            raise ValueError("乘法错误:左矩阵列数必须等于右矩阵行数!")
        # 创建全0的结果矩阵
        mul_result = [[0 for _ in range(other_mat.col_num)] for _ in range(self.row_num)]
        # 三层循环计算矩阵乘积
        for i in range(self.row_num):
            for j in range(other_mat.col_num):
                sum_val = 0
                for k in range(self.col_num):
                    sum_val += self.data[i][k] * other_mat.data[k][j]
                mul_result[i][j] = sum_val
        return Matrix(mul_result)


# 主程序入口,分步演示全部运算
if __name__ == "__main__":
    print("==================== 题目演示开始 ====================")
    # 1. 定义测试矩阵
    print("1. 定义原始矩阵A:")
    mat_a = Matrix([
        [1, 2, 3],
        [4, 5, 6]
    ])
    mat_a.print_matrix()

    print("\n定义原始矩阵B(用于加减运算):")
    mat_b = Matrix([
        [1, 1, 1],
        [2, 2, 2]
    ])
    mat_b.print_matrix()

    print("\n定义原始矩阵C(用于乘法运算):")
    mat_c = Matrix([
        [1, 2],
        [3, 4],
        [5, 6]
    ])
    mat_c.print_matrix()

    # 2. 矩阵转置运算演示
    print("\n==================== 运算1:矩阵A转置 ====================")
    trans_a = mat_a.transpose_matrix()
    print("矩阵A转置结果:")
    trans_a.print_matrix()

    # 3. 矩阵加法演示
    print("\n==================== 运算2:矩阵A + 矩阵B ====================")
    try:
        add_ab = mat_a.add_matrix(mat_b)
        print("A+B 的结果:")
        add_ab.print_matrix()
    except ValueError as err:
        print(err)

    # 4. 矩阵减法演示
    print("\n==================== 运算3:矩阵A - 矩阵B ====================")
    try:
        sub_ab = mat_a.sub_matrix(mat_b)
        print("A-B 的结果:")
        sub_ab.print_matrix()
    except ValueError as err:
        print(err)

    # 5. 矩阵乘法演示
    print("\n==================== 运算4:矩阵A × 矩阵C ====================")
    try:
        mul_ac = mat_a.mul_matrix(mat_c)
        print("A×C 的结果:")
        mul_ac.print_matrix()
    except ValueError as err:
        print(err)
    print("==================== 全部运算演示结束 ====================")

image

 

  

 

 2025010113 石蕊鑫

截取字符串的子串

def cut_substring(s, start, end):
    # s:原字符串;start:开始;end:结束
    return s[start:end]

my_str = "我爱学习"
result = cut_substring(my_str, 1, 4)
print("截取结果:", result)

屏幕截图 2026-05-24 225308

2025010114 殷佳锐

通讯录

# 定义通讯录(用字典存储,键是联系人姓名,值是包含电话和备注的字典)
address_book = {}
# 1. 查看所有联系人的函数
def show_all_contacts():
    print("\n===== 通讯录列表 =====")
    if not address_book:
        print("通讯录为空~")
        return
    for name, info in address_book.items():
        print(f"姓名:{name} | 电话:{info['phone']} | 备注:{info['note']}")
    print("======================\n")
# 2. 添加联系人的函数
def add_contact(name, phone, note="无"):
    """
    添加联系人到通讯录
    :param name: 联系人姓名(唯一)
    :param phone: 联系人电话
    :param note: 备注信息,默认"无"
    """
    if name in address_book:
        print(f"❌ 联系人【{name}】已存在,无法重复添加!")
    else:
        address_book[name] = {
            "phone": phone,
            "note": note
        }
        print(f"✅ 联系人【{name}】添加成功!")
# 3.主菜单函数
def main():
    while True:
        print("===== 简易通讯录 =====")
        print("1. 查看所有联系人")
        print("2. 添加联系人")
        print("3. 退出程序")
        choice = input("请输入你的选择(1/2/3):")
        if choice == "1":
            show_all_contacts()
        elif choice == "2":
            name = input("请输入联系人姓名:")
            phone = input("请输入联系人电话:")
            note = input("请输入备注(可不填,直接回车默认'无'):")
            if note.strip() == "":
                note = "无"
            add_contact(name, phone, note)
        elif choice == "3":
            print("👋 退出通讯录,再见!")
            break
        else:
            print("❌ 输入无效,请输入1/2/3!\n")
# 启动程序
if __name__ == "__main__":
     main()

联想截图_20260520112248

 

 2025010115  康静茹

写一个计费单,通过汇率转换输出个公司收益情况

# 1. 汇率表(可自行修改)
rate = {
    "韩国": 0.0052,
    "英国": 8.72,
    "美国": 7.23,
    "日本": 0.043
}

# 2. 空列表存订单
orders = []

# 3. 核心:添加订单并自动换算
def add_order(order_id, company, country, foreign_money):
    # 换算人民币,没有对应国家则按0元处理
    rmb = foreign_money * rate.get(country, 0)
    orders.append([order_id, company, country, foreign_money, round(rmb, 2)])

# 4. 录入订单数据(可自行增删)
add_order("NO.001", "A公司", "韩国", 10000)
add_order("NO.002", "B公司", "英国", 500)
add_order("NO.003", "C公司", "美国", 2000)

# 5. 打印订单名单 + 汇总
def print_bill():
    print("==== 国际订单计费单 ====")
    print("订单号 | 公司 | 国家 | 外币金额 | 人民币")
    print("-" * 40)
    total = 0
    for order in orders:
        print(f"{order[0]} | {order[1]} | {order[2]} | {order[3]} | {order[4]}")
        total += order[4]
    print("-" * 40)
    print(f"订单总数:{len(orders)} 笔")
    print(f"总金额:{round(total, 2)} 元人民币")

# 运行
print_bill()

局部截取_20260520_114237

2025010117  李欣栎

日期加减

# 2026年是平年,每月天数
md = [31,28,31,30,31,30,31,31,30,31,30,31]

# 1. 日期 → 当年第几天(只处理2026年)
def riqi_days(m, d):
    total = 0
    # 累加前面月份的天数
    for i in range(m-1):
        total += md[i]
    total += d# 加上当月的天数
    return total

# 2. 当年第几天 → 日期(只处理2026年)
def days_riqi(n):
    m = 0
    while True:
        day = md[m]
        if n > day:
            n -= day
            m += 1
        else:
            break
    return m+1, n


# 2026年5月1日
m1, d1 = 5, 1

# 1. 转成当年的第几天
t1 = riqi_days(m1, d1)
print("2026年5月1日 是2026年的第", t1, "天")

# 2. 日期 + 天数:加3天
jia = t1 + 6
nm, nd = days_riqi(jia)
print("2026年5月1日加3天:", "2026年", nm, "月", nd, "日")

# 3. 日期 - 天数:减2天
jian = t1 - 2
nm2, nd2 = days_riqi(jian)
print("2026年5月1日减2天:", "2026年", nm2, "月", nd2, "日")

# 4. 日期 - 日期:求相差天数(今年内)
m2, d2 = 5, 10
t2 = riqi_days(m2, d2)
cha = t2 - t1
print("2026年5月1日和5月10日相差:", cha, "天")

b974708f8aba05edd0973f5623b12ece

 

 

2025010118   陈影

绘制三维网兜

import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
# 生成网格基础数据
u = np.linspace(-1, 1, 30)
v = np.linspace(-1, 1, 30)
U, V = np.meshgrid(u, v)
# 四角拉扯变形,做出带棱角的方形网兜
X = U * (1 + 0.2 * V**2)
Y = V * (1 + 0.2 * U**2)
# 开口朝下、自然下坠的兜形曲面
Z = 0.6 * (U**2 + V**2)
# alpha=透明度,1=完全不透明,越小越通透
ax.plot_surface(
    X, Y, Z,
    color='#7EC0EE',   # 柔和天蓝色
    alpha=0.8,         # 半透明质感
    edgecolor='none'   # 网格边线,完全看不出网状
)
#基础美化
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_title('彩色实心三维网兜')
#调整最佳观看视角
ax.view_init(elev=30, azim=45)
plt.tight_layout()
plt.show()

image

2025010119淡郑雪

爬虫  豆瓣前十个

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
}

# 豆瓣Top250第一页
url = "https://movie.douban.com/top250"
res = requests.get(url, headers=headers)
res.encoding = "utf-8"
soup = BeautifulSoup(res.text, "html.parser")

# 提取前10部电影
movie_list = soup.find_all("div", class_="item")
print("豆瓣电影Top10:\n")

for i, movie in enumerate(movie_list[:10], 1):
    title = movie.find("span", class_="title").text.strip()
    score = movie.find("span", class_="rating_num").text
    info = movie.find("div", class_="bd").p.text.strip()
    print(f"{i}. {title}  评分:{score}")
    print(f"   {info[:60]}...\n")

屏幕截图 2026-06-10 102013

 

 2025010121郑舒萍

左边列商品表,右边列购物表,结合两个表推荐一个类似种类的商品

# 左:商品表数据
goods = [
    [1, "三体", "科幻"],
    [2, "流浪地球", "科幻"],
    [3, "银河帝国", "科幻"],
    [4, "活着", "文学"],
    [5, "围城", "文学"],
    [6, "平凡的世界", "文学"],
    [7, "Python入门", "编程"],
    [8, "Java教程", "编程"]
]
# 右:购物表数据
buy = [1, 2]

# 打印商品表格
print("=====【商品表】=====")
print("编号\t书名\t\t分类")
for item in goods:
    print(f"{item[0]}\t{item[1]}\t{item[2]}")

# 打印购物表格
print("\n=====【购物表(已买编号)】=====")
print("已购编号")
for n in buy:
    print(n)

# 推荐逻辑
kind = ""
for i in goods:
    if i[0] == buy[0]:
        kind = i[2]

res = []
for i in goods:
    if i[2] == kind and i[0] not in buy:
        res.append(i[1])

# 打印推荐结果
print("\n=====推荐商品=====")
print(res)

屏幕截图 2026-06-03 112540

2025010122 田昌盛 全局局部储存动画展示

#全局局部变量演示
a=100
def func():
    global a
    b=200
    a=999
    print('内部a',a,'b',b)
func()
print('外部a',a)
#嵌套nonlocal
def outer():
    x=10
    def inner():
        nonlocal x
        y=20
        x=100
        print('inner x',x,'y',y)
    inner()
    print('outer x',x)
outer()

 屏幕截图 2026-06-05 195958

 

 

2025010124 胡鑫

文件夹分类

import os
import random

# 1. 定义三个分类文件夹名称
folder_small = "小型文件"
folder_mid = "中型文件"
folder_big = "大型文件"

# 创建文件夹,不存在则自动新建
for folder in [folder_small, folder_mid, folder_big]:
    if not os.path.exists(folder):
        os.mkdir(folder)

# 2. 生成不同大小的测试文件
def create_random_file(filename, size_kb):
    """创建指定大小的空白文件"""
    with open(filename, "wb") as f:
        f.write(b"0" * 1024 * size_kb)

# 自定义几组不同大小文件(单位KB)
file_size_list = [20, 80, 150, 500, 1200, 2500, 60]

# 批量生成文件
for idx, size in enumerate(file_size_list):
    file_name = f"测试文件{idx+1}.txt"
    create_random_file(file_name, size)

# 3. 根据文件大小自动分类移动
def sort_file_by_size(file_path):
    file_size = os.path.getsize(file_path) / 1024  # 转为KB

    if file_size < 100:
        target_dir = folder_small
    elif 100 <= file_size <= 1024:
        target_dir = folder_mid
    else:
        target_dir = folder_big

    new_path = os.path.join(target_dir, os.path.basename(file_path))
    os.rename(file_path, new_path)

# 遍历当前目录所有文件进行分类
for file in os.listdir("./"):
    if file.endswith(".txt"):
        sort_file_by_size(file)

print("文件大小分类完成!")

截屏2026-05-26 23.05.55

2025010125   刘芮孜

import tkinter as tk
from tkinter import ttk, filedialog
import winsound
import os

class MusicPlayer:
    def __init__(self, root):
        self.root = root
        self.root.title("Python音乐播放器")
        self.root.geometry("500x400")

        self.playlist = []
        self.current_idx = 0
        self.is_playing = False

        self.create_widgets()

    def create_widgets(self):
        self.listbox = tk.Listbox(self.root, width=60, height=10)
        self.listbox.pack(pady=10)

        frame = tk.Frame(self.root)
        frame.pack()

        tk.Button(frame, text="打开文件", command=self.load_music).grid(row=0, column=0, padx=5)
        tk.Button(frame, text="上一曲", command=self.prev_song).grid(row=0, column=1, padx=5)
        self.play_btn = tk.Button(frame, text="播放", command=self.toggle_play)
        self.play_btn.grid(row=0, column=2, padx=5)
        tk.Button(frame, text="下一曲", command=self.next_song).grid(row=0, column=3, padx=5)

        self.vol_slider = ttk.Scale(self.root, from_=0, to=100, orient="horizontal")
        self.vol_slider.set(50)
        self.vol_slider.pack(fill="x", padx=20, pady=5)

        self.progress = ttk.Scale(self.root, from_=0, to=100, orient="horizontal")
        self.progress.pack(fill="x", padx=20, pady=5)

    def load_music(self):
        files = filedialog.askopenfilenames(filetypes=[("音频文件", "*.wav")])
        for f in files:
            self.playlist.append(f)
            self.listbox.insert(tk.END, os.path.basename(f))

    def play_song(self):
        if not self.playlist:
            return
        winsound.PlaySound(self.playlist[self.current_idx], winsound.SND_FILENAME | winsound.SND_ASYNC)
        self.is_playing = True
        self.play_btn.config(text="暂停")

    def toggle_play(self):
        if not self.playlist:
            return
        if self.is_playing:
            winsound.PlaySound(None, winsound.SND_PURGE)
            self.is_playing = False
            self.play_btn.config(text="播放")
        else:
            self.play_song()

    def prev_song(self):
        if self.current_idx > 0:
            self.current_idx -= 1
            self.play_song()

    def next_song(self):
        if self.current_idx < len(self.playlist)-1:
            self.current_idx += 1
            self.play_song()

if __name__ == "__main__":
    root = tk.Tk()
    app = MusicPlayer(root)
    root.mainloop()

111

 

 2025010128  贾姝慧

  协方差函数

# 温度、气压 物理实验数据
temp = [18, 20, 22, 24, 26, 28]
press = [100.9, 101.1, 101.4, 101.7, 102.0, 102.3]

# 协方差计算函数
def calc_cov(x, y):
    n = len(x)
    mean_x = sum(x) / n
    mean_y = sum(y) / n
    total = sum((i - mean_x) * (j - mean_y) for i, j in zip(x, y))
    return total / (n - 1)

# 计算并输出
cov_value = calc_cov(temp, press)
print("协方差:", round(cov_value, 3))

屏幕截图 2026-05-26 234221

 2025010130任鸿杰

美团


# 订单状态枚举(提高代码可读性)
class OrderStatus:
PENDING_PAY = "待支付"
PAID = "已支付,待商家接单"
MERCHANT_ACCEPTED = "商家已接单,待骑手接单"
RIDER_ACCEPTED = "骑手已接单,待取餐"
RIDER_PICKED = "骑手已取餐,配送中"
COMPLETED = "已完成"
CANCELLED = "已取消"


class User:
"""用户基类:所有用户的公共属性"""
def __init__(self, name, phone):
self.name = name
self.phone = phone

def __str__(self):
return f"姓名:{self.name},电话:{self.phone}"


class Merchant(User):
"""商家类:继承用户类,负责商品管理、接单、备餐"""
def __init__(self, name, phone, shop_name, address):
super().__init__(name, phone)
self.shop_name = shop_name # 店铺名称
self.address = address # 店铺地址
self.goods = [] # 店铺商品列表

# 商家发布商品
def add_goods(self, goods_name, price):
self.goods.append({"name": goods_name, "price": price})
print(f"【{self.shop_name}】发布新品:{goods_name},价格:{price}元")

# 商家接单
def accept_order(self, order):
if order.status == OrderStatus.PAID:
order.status = OrderStatus.MERCHANT_ACCEPTED
print(f"✅【{self.shop_name}】已接单,开始备餐")
else:
print(f"❌ 订单状态异常,无法接单")

def __str__(self):
return f"商家:{self.shop_name},地址:{self.address},联系人:{self.name}"


class Customer(User):
"""顾客类:继承用户类,负责下单、支付、确认收货"""
def __init__(self, name, phone, address):
super().__init__(name, phone)
self.address = address # 收货地址

# 顾客创建订单
def create_order(self, merchant, goods_list):
order = Order(self, merchant, goods_list)
print(f"\n📝 【{self.name}】创建订单:{order}")
return order

# 顾客支付订单
def pay_order(self, order):
if order.status == OrderStatus.PENDING_PAY:
order.status = OrderStatus.PAID
print(f"✅【{self.name}】支付成功,订单金额:{order.total_price}元")
else:
print(f"❌ 订单无需支付或已取消")

# 顾客确认收货
def confirm_receipt(self, order):
if order.status == OrderStatus.RIDER_PICKED:
order.status = OrderStatus.COMPLETED
print(f"\n🎉【{self.name}】确认收货,订单完成!")
else:
print(f"❌ 订单无法确认收货")

def __str__(self):
return f"顾客:{self.name},收货地址:{self.address}"


class Rider(User):
"""骑手类:继承用户类,负责接单、取餐、配送"""
def __init__(self, name, phone, rider_id):
super().__init__(name, phone)
self.rider_id = rider_id # 骑手编号
self.current_order = None # 当前配送的订单

# 骑手接单
def take_order(self, order):
if order.status == OrderStatus.MERCHANT_ACCEPTED:
self.current_order = order
order.status = OrderStatus.RIDER_ACCEPTED
print(f"🚀【骑手{self.name}】已接单,前往商家取餐")
else:
print(f"❌ 订单状态异常,无法接单")

# 骑手取餐
def pick_up_food(self):
if self.current_order and self.current_order.status == OrderStatus.RIDER_ACCEPTED:
self.current_order.status = OrderStatus.RIDER_PICKED
print(f"🍱【骑手{self.name}】已取餐,开始配送")
else:
print(f"❌ 无有效订单可取餐")

def __str__(self):
return f"骑手:{self.name},编号:{self.rider_id}"


class Order:
"""订单类:核心业务载体,关联顾客、商家、骑手、商品"""
def __init__(self, customer, merchant, goods_list):
self.customer = customer # 下单顾客
self.merchant = merchant # 接单商家
self.goods_list = goods_list# 购买商品
self.total_price = sum(goods["price"] for goods in goods_list) # 订单总价
self.status = OrderStatus.PENDING_PAY # 初始状态:待支付
self.rider = None # 接单骑手

# 绑定骑手
def bind_rider(self, rider):
self.rider = rider

def __str__(self):
goods_names = "、".join([g["name"] for g in self.goods_list])
return (f"订单详情:商家【{self.merchant.shop_name}】,商品【{goods_names}】,"
f"总价:{self.total_price}元,状态:{self.status}")


# ===================== 模拟美团外卖完整流程 =====================
if __name__ == '__main__':
# 1. 创建商家
merchant = Merchant("王老板", "13800138000", "黄焖鸡米饭(科技园店)", "深圳市南山区科技园")
# 商家发布商品
merchant.add_goods("招牌黄焖鸡", 25)
merchant.add_goods("可乐", 5)

# 2. 创建顾客
customer = Customer("小明", "13900139000", "深圳市南山区腾讯大厦")

# 3. 创建骑手
rider = Rider("小李", "13700137000", "QD8888")

print("\n==================== 开始下单流程 ====================")
# 4. 顾客挑选商品,创建订单
select_goods = [merchant.goods[0], merchant.goods[1]] # 选黄焖鸡+可乐
order = customer.create_order(merchant, select_goods)

# 5. 顾客支付订单
customer.pay_order(order)

# 6. 商家接单备餐
merchant.accept_order(order)

# 7. 系统绑定骑手 + 骑手接单
order.bind_rider(rider)
rider.take_order(order)

# 8. 骑手取餐并配送
rider.pick_up_food()

# 9. 顾客确认收货
customer.confirm_receipt(order)
 

屏幕截图 2026-06-17 130444

 

2025010131   董玥卓

类,二进制数的与或非

class BinaryCalc:
    def __init__(self, num1=0, num2=0):
        self.n1 = num1
        self.n2 = num2

    # 按位与 &
    def bit_and(self):
        res = self.n1 & self.n2
        return bin(res), res

    # 按位或 |
    def bit_or(self):
        res = self.n1 | self.n2
        return bin(res), res

    # 按位非 ~ (补码形式)
    def bit_not(self, num):
        res = ~num
        return bin(res), res


# 调用示例
if __name__ == "__main__":
    b = BinaryCalc(6, 3)  # 6=0b110 ,3=0b011
    print("与运算(二进制,十进制):", b.bit_and())
    print("或运算(二进制,十进制):", b.bit_or())
    print("非6(二进制,十进制):", b.bit_not(6))
    print("非3(二进制,十进制):", b.bit_not(3))

屏幕截图 2026-06-03 102352

 2025010132  李佳雨

矩阵

import numpy as np

# 1. 矩阵转置演示
A = np.array([[1, 2, 3],
              [4, 5, 6]])
A_T = A.T  # 矩阵转置
print("原矩阵A:")
print(A)
print("A的转置A^T:")
print(A_T)

# 2. 向量单位化(归一化)演示
alpha = np.array([3, 4])
norm = np.linalg.norm(alpha)  # 求向量模长
beta = alpha / norm           # 单位化
print("\n原向量α:", alpha)
print("单位化后β:", beta)
print("β的模:", np.linalg.norm(beta))

# 3. 补充:特殊矩阵构造(单位矩阵、对角矩阵)
E3 = np.eye(3)        # 3阶单位矩阵
D = np.diag([1,2,3])  # 对角矩阵
print("\n3阶单位矩阵:")
print(E3)
print("对角矩阵:")
print(D)

 

屏幕截图 2026-06-05 220700

 

posted @ 2026-06-17 21:33  szmtjs10  阅读(4)  评论(0)    收藏  举报