python第四次作业

  1. 位运算:计算 56 及 - 18 的所有位运算符结果,并使在注释中体现计算过程
python 复制代码
# 56的原码: 00111000  -18的源码:10010010 反码:11101101 补码:11101110
# & 与 
# 00111000 & 11101110 = 00101000
# 00111000 | 11101110 = 11111110
# 00111000 ^ 11101110 = 11010110
  1. 完成文件读取功能,任意读取某个文件内容时,请编写装饰器,实现写出文件时增加当前系统时间,并打印至控制台最后一行
python 复制代码
import time
class wirte_file2():
    def __init__(self,time):
        self.time = time
    def __call__(self,func):
        def wrapper(*args, **kwargs):
            with open("../test_log.txt", "a+") as f:
                f.write(f"time:{self.time}\n")
            func(*args, **kwargs)
        return wrapper

@wirte_file2(time = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()) )
def test3(str):
    with open("../test_log.txt", "a+") as f:
        f.write(str)

test3("a\n")
  1. 给定一个包含 n+1 个整数的数组 nums,其数字在 1 到 n 之间 (包含 1 和 n),可知至少存在一个重复的整数 假设只有一个重复的整数,请找出这个重复的数
python 复制代码
def find_duplicate(nums):
    nums.sort()
    for i in range(1,len(nums)):
        if nums[i] == nums[i-1]:
            return nums[i]
    return -1

nums1 = [1, 3, 4, 2,2]
print(find_duplicate(nums1))

运行结果:

  1. 完成登录系统,登录时数据使用序列化和反序列化.
python 复制代码
import pickle
import os

USER_FILE = "users.pkl"
# 初始化用户文件
if not os.path.exists(USER_FILE):
    with open(USER_FILE, 'wb') as f:
        pickle.dump({}, f)

def register(username, password):
    with open(USER_FILE, 'rb') as f:
        users = pickle.load(f)
    if username in users:
        return "用户名已存在"
    users[username] = password
    with open(USER_FILE, 'wb') as f:
        pickle.dump(users, f)
    return "注册成功"

def login(username, password):
    with open(USER_FILE, 'rb') as f:
        users = pickle.load(f)
    if username not in users:
        return "用户名不存在"
    return "登录成功" if users[username] == password else "密码错误"

register("user1", "123456")
login("user1", "123456") 

运行结果:

相关推荐
IVEN_1 小时前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang2 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮2 小时前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling2 小时前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python
AI攻城狮6 小时前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽6 小时前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健21 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞1 天前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽1 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers