- 位运算:计算 56 及 - 18 的所有位运算符结果,并使在注释中体现计算过程
python
# 56的原码: 00111000 -18的源码:10010010 反码:11101101 补码:11101110
# & 与
# 00111000 & 11101110 = 00101000
# 00111000 | 11101110 = 11111110
# 00111000 ^ 11101110 = 11010110
- 完成文件读取功能,任意读取某个文件内容时,请编写装饰器,实现写出文件时增加当前系统时间,并打印至控制台最后一行
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")
- 给定一个包含 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))
运行结果:

- 完成登录系统,登录时数据使用序列化和反序列化.
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")
运行结果:
