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") 

运行结果:

相关推荐
小小测试开发1 天前
安装 Python 3.10+
开发语言·人工智能·python
梦想不只是梦与想1 天前
Python 中的装饰器
python·装饰器
我叫唧唧波1 天前
Python+AI 全栈学习笔记
人工智能·python·学习
AAA大运重卡何师傅(专跑国道)1 天前
【无标题】
开发语言·c#
copyer_xyf1 天前
Python 异常处理
前端·后端·python
XBodhi.1 天前
Visual Studio C++ 语法错误: 缺少“;”(在“return”的前面)
开发语言·c++·visual studio
麻雀飞吧1 天前
期货多合约策略目标持仓怎么更新才不乱
python·区块链
Cthy_hy1 天前
拓扑排序超详解:原理 + Kahn 贪心算法
python·算法·贪心算法
LSssT.1 天前
【01】Python 机器学习
开发语言·python
为爱停留1 天前
给智能体装上「刹车」:中断(Interrupts)与人工审批全解析
python