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

运行结果:

相关推荐
Norna1 小时前
Git 给路径加了引号,这个文件就从 review 里消失了
python
wuyk5551 小时前
Python办公自动化-第04讲-批量新建Excel
开发语言·python·excel
wuyk5551 小时前
Spider-第20讲-综合实战可上线爬虫
大数据·爬虫·python·elasticsearch
code2cat2 小时前
【随笔】Java客户端选了HTTP/3,怎样知道请求实际走了哪个版本
java·开发语言·http
JonaHu2 小时前
关键词排名突然消失?用 Python、SQLite 和 SERP API 搭一套可解释的 SEO 监控
python·sqlite·seo·serp api
prince_zxill3 小时前
把 17 个散文件装进一个文件夹:拆解 claude-plugins-official 的插件打包术(47,413 Star 实测)
python·github·agent·mcp·claude code
少司府3 小时前
嵌入式外设篇(三)GPIO·三:MCU系统结构、总线与统一编制
linux·python·stm32·单片机·嵌入式硬件·mcu·嵌入式软件
伞伞悦读4 小时前
【第90期】KNN分类回归流水线与K值对照的实验与排查
大数据·人工智能·python·深度学习·机器学习
console.log('npc')5 小时前
Python 学习教程 · 第4课:数据结构
数据结构·python·学习
honker_X5 小时前
Python字符串全攻略:从入门到精通
开发语言·python