[第四次作业]
1.每日一讲每日一讲2.位运算 计算56及-18的所有位运算符结果并使在注释中体现计算过程 计算 56 和 -18 的所有位运算符结果 # 56 的二进制表示: 0011 1000 (8位) # -18 的二进制表示(补码): 1110 1110 (8位) print( * 50) print(56 和 -18 的位运算结果) print( * 50) # 1. 按位与 () # 56 -18 # 0011 1000 (56) # 1110 1110 (-18) # ---------- # 0010 1000 (40) result_and 56 -18 print(f56 -18 {result_and} # 二进制: 0010 1000) # 2. 按位或 (|) # 56 | -18 # 0011 1000 (56) # 1110 1110 (-18) # ---------- # 1111 1110 (-2) result_or 56 | -18 print(f56 | -18 {result_or} # 二进制: 1111 1110) # 3. 按位异或 (^) # 56 ^ -18 # 0011 1000 (56) # 1110 1110 (-18) # ---------- # 1101 0110 (-42) result_xor 56 ^ -18 print(f56 ^ -18 {result_xor} # 二进制: 1101 0110) # 4. 按位取反 (~) # ~56 # ~0011 1000 1100 0111 -57 result_not_56 ~56 print(f~56 {result_not_56} # 二进制: 1100 0111) # ~-18 # ~1110 1110 0001 0001 17 result_not_neg18 ~-18 print(f~-18 {result_not_neg18} # 二进制: 0001 0001) # 5. 左移位 () # 56 2 56 * 2^2 224 # 0011 1000 2 1110 0000 (224) result_left_56 56 2 print(f56 2 {result_left_56} # 二进制: 1110 0000) # -18 2 -18 * 2^2 -72 # 1110 1110 2 1011 1000 (-72) result_left_neg18 -18 2 print(f-18 2 {result_left_neg18} # 二进制: 1011 1000) # 6. 右移位 () # 56 2 56 // 2^2 14 # 0011 1000 2 0000 1110 (14) result_right_56 56 2 print(f56 2 {result_right_56} # 二进制: 0000 1110) # -18 2 -18 // 2^2 -5 # 1110 1110 2 1111 1011 (-5) result_right_neg18 -18 2 print(f-18 2 {result_right_neg18} # 二进制: 1111 1011) print( * 50)3.完成文件读取功能任意读取某个文件内容时请编写装饰器实现写出文件时增加当前系统时间并打印至控制台最后一行import os from datetime import datetime from functools import wraps def log_file_read(func): 装饰器记录文件读取操作并在控制台打印时间戳 wraps(func) def wrapper(*args, **kwargs): # 获取当前系统时间 current_time datetime.now().strftime(%Y-%m-%d %H:%M:%S) # 执行原函数 result func(*args, **kwargs) # 打印时间戳到控制台最后一行 print(f\n[系统时间] {current_time}) print(f文件读取完成) return result return wrapper log_file_read def read_file(file_path): try: with open(file_path, r, encodingutf-8) as f: content f.read() print(f成功读取文件: {file_path}) return content except FileNotFoundError: error_msg f错误: 文件 {file_path} 不存在 print(error_msg) return error_msg except PermissionError: error_msg f错误: 没有权限读取文件 {file_path} print(error_msg) return error_msg except Exception as e: error_msg f读取文件时出错: {e} print(error_msg) return error_msg log_file_read def read_file_lines(file_path): try: with open(file_path, r, encodingutf-8) as f: lines f.readlines() print(f成功读取文件: {file_path}) print(f文件行数: {len(lines)} 行) return lines except FileNotFoundError: error_msg f错误: 文件 {file_path} 不存在 print(error_msg) return error_msg except Exception as e: error_msg f读取文件时出错: {e} print(error_msg) return error_msg # 测试代码 if __name__ __main__: print( * 60) print(文件读取测试) print( * 60) # 创建测试文件 test_file test_read.txt test_content 这是测试文件的第一行 这是第二行 这是第三行 文件读取测试示例 # 创建测试文件 with open(test_file, w, encodingutf-8) as f: f.write(test_content) print(f已创建测试文件: {test_file}) # 测试1: 读取整个文件 print(\n - * 40) print(测试1: 读取整个文件) print(- * 40) content read_file(test_file) print(f\n文件内容:\n{content})4.给定一个包含n1个整数的数组nums其数字在1到n之间(包含1和n),可知至少存在一个重复的整数 假设只有一个重复的整数请找出这个重复的数def find_duplicate(nums): def method_binary_search(nums): left, right 1, len(nums) - 1 while left right: mid (left right) // 2 count sum(1 for num in nums if num mid) if count mid: right mid else: left mid 1 return left print(f使用二分查找法: {method_binary_search(nums)}) # 测试 if __name__ __main__: nums1 [1, 3, 4, 2, 2] print( * 50) print(f测试: 重复数是 {find_duplicate(nums1)})5.完成登录系统登录时数据使用序列化和反序列化import json import os import hashlib from datetime import datetime class LoginSystem: 登录系统使用JSON序列化存储用户数据 def __init__(self, data_fileusers.json): self.data_file data_file self.users {} self.current_user None self.load_users() def hash_password(self, password): 对密码进行哈希加密 return hashlib.sha256(password.encode()).hexdigest() def load_users(self): 反序列化从文件加载用户数据 if os.path.exists(self.data_file): try: with open(self.data_file, r, encodingutf-8) as f: self.users json.load(f) print(f成功加载用户数据共 {len(self.users)} 个用户) except Exception as e: print(f加载用户数据失败: {e}) self.users {} else: print(用户数据文件不存在创建新文件) self.users {} def save_users(self): 序列化将用户数据保存到文件 try: with open(self.data_file, w, encodingutf-8) as f: json.dump(self.users, f, ensure_asciiFalse, indent2) print(f用户数据已保存到 {self.data_file}) return True except Exception as e: print(f保存用户数据失败: {e}) return False def register(self, username, password): 注册新用户 if username in self.users: print(f用户名 {username} 已存在) return False if not username or not password: print(用户名和密码不能为空) return False self.users[username] { password: self.hash_password(password), created_at: datetime.now().strftime(%Y-%m-%d %H:%M:%S), last_login: None } if self.save_users(): print(f用户 {username} 注册成功) return True return False def login(self, username, password): 用户登录 if username not in self.users: print(f用户名 {username} 不存在) return False user self.users[username] if user[password] self.hash_password(password): self.current_user username user[last_login] datetime.now().strftime(%Y-%m-%d %H:%M:%S) self.save_users() print(f用户 {username} 登录成功) print(f上次登录时间: {user[last_login]}) return True else: print(密码错误) return False def logout(self): 退出登录 if self.current_user: print(f用户 {self.current_user} 已退出) self.current_user None else: print(当前没有用户登录) def delete_user(self, username): 删除用户 if username not in self.users: print(f用户 {username} 不存在) return False if self.current_user username: print(不能删除当前登录的用户) return False del self.users[username] if self.save_users(): print(f用户 {username} 已删除) return True return False def list_users(self): 列出所有用户 if not self.users: print(当前没有用户) return print(\n * 60) print(用户列表:) print(- * 60) for username, info in self.users.items(): print(f用户名: {username}) print(f 创建时间: {info[created_at]}) print(f 上次登录: {info[last_login] or 从未登录}) print(- * 60) print( * 60) def show_current_user(self): 显示当前登录用户 if self.current_user: print(f当前登录用户: {self.current_user}) user self.users[self.current_user] print(f 创建时间: {user[created_at]}) print(f 上次登录: {user[last_login]}) else: print(当前没有用户登录) def main(): 主函数 - 交互式登录系统 system LoginSystem() while True: print(\n * 50) print(登录系统菜单) print( * 50) print(1. 注册) print(2. 登录) print(3. 显示当前用户) print(4. 列出所有用户) print(5. 删除用户) print(6. 退出登录) print(7. 退出系统) print( * 50) choice input(请选择操作 (1-7): ).strip() if choice 1: username input(请输入用户名: ).strip() password input(请输入密码: ).strip() system.register(username, password) elif choice 2: username input(请输入用户名: ).strip() password input(请输入密码: ).strip() system.login(username, password) elif choice 3: system.show_current_user() elif choice 4: system.list_users() elif choice 5: username input(请输入要删除的用户名: ).strip() system.delete_user(username) elif choice 6: system.logout() elif choice 7: print(感谢使用再见) break else: print(无效的选择请重新输入) if __name__ __main__: main()