Python 4

📅 2026/8/12 16:07:09
Python 4
第一题 位运算计算56及-18的所有位运算符结果并使在注释中体现计算过程【代码】x 56 y -18 # 位与 56: 0011 1000 -18:1110 1110 x y: 0010 1000 print(fx y {x y}) # 位或| 56: 0011 1000 -18:1110 1110 x | y: 1111 1110补 1111 1101反 0000 0010原 print(fx | y {x | y}) # 位非~ 56: 0011 1000 -56:1100 0111 -18:1110 1110 18: 0001 0001 print(f~x {~x}) print(f~y {~y}) # 异或^ 56: 0011 1000 -18:1110 1110 x ^ y: 1101 0110补 1101 0101反 0010 1010原 print(fx ^ y {x ^ y}) # 左移 56: 0011 1000 562: 1110 0000 -18:1110 1110 -182: 1011 1000 print(fx 2 {x 2}) print(fy 2 {y 2}) # 右移 56: 0011 1000 562: 0000 1110 -18:1110 1110 -182: 1111 1011补 1111 1010反 0000 00101原 print(fx 2 {x 2}) print(fy 2 {y 2})【运行结果】第二题 完成文件读取功能任意读取某个文件内容时请编写装饰器实现写出文件时增加当前系统时间并打印至控制台最后一行【代码】import time def add_timestamp(func): def wrapper(filepath): with open(filepath, r, encodingutf-8) as f: content f.read() now time.strftime(%Y-%m-%d %H:%M:%S, time.localtime()) new_file filepath.replace(.txt, _with_time.txt) with open(new_file, w, encodingutf-8) as f: f.write(content f\n[读取时间] {now}) print(f当前时间: {now}) return content return wrapper add_timestamp def read_file(filepath): with open(filepath, r, encodingutf-8) as f: return f.read() if __name__ __main__: content read_file(test.txt) print(内容:\n,content)【运行结果】第三题 给定一个包含n1个整数的数组nums其数字在1到n之间(包含1和n),可知至少存在一个重复的整数 假设只有一个重复的整数请找出这个重复的数【代码】def lst(nums): re set() for num in nums: if num in re: return num re.add(num) nums [1,2,3,4,5,1,6,7,8,1,9,10] print(lst(nums))【运行结果】第四题 完成登录系统登录时数据使用序列化和反序列化【代码】import pickle import os user_date xxx def load_users(): if os.path.exists(user_date): with open(user_date, rb) as f: return pickle.load(f) return {} def save_users(users): with open(user_date, wb) as f: pickle.dump(users, f) def register(): username input(用户名: ) password input(密码: ) users load_users() if username in users: print(注册失败,用户已存在) return users[username] password save_users(users) print( 注册成功) def login(): username input(用户名: ) password input(密码: ) users load_users() if users.get(username) password: print( 登录成功) else: print( 用户名或密码错误) while True: print(\n1. 注册 2. 登录 3. 退出) choice input(请选择: ) if choice 1: register() elif choice 2: login() elif choice 3: break else: print( 无效输入)【运行结果】