一、计算文件大小
import os
def get_size(path):
size = 0
l = [path]
while l:
path = l.pop()
lst = os.listdir(path)
for name in lst:
son_path = os.path.join(path,name)
if os.path.isfile(son_path):
size += os.path.getsize(son_path)
else:
l.append(son_path)
return size
size = get_size(r'D:\s14\算法')
print(size)
二、三级菜单
l = [menu]
while l:
for k in l[-1]:
print(k)
key = input('>>>')
if key.upper() == 'B':
l.pop()
elif key.upper() == 'Q':
l.clear()
elif l[-1].get(key):
l.append(l[-1][key])
三、文件监听
def func():
with open('test.txt', 'r+', encoding='utf-8') as f:
while 1:
lens = f.readline()
if lens:
yield lens
t = func()
for j in t:
print(j)
四、发红包
import random
def rea_pac(money,num):
ret = random.sample(range(1,money*100),num-1)
print(ret)
ret.sort()
ret.insert(0,0)
ret.append(money*100)
for i in range(len(ret)-1):
value = ret[i+1] - ret[i]
yield value/100
g = rea_pac(200,10)
for i in g:
print(i)
五、递归问路
lis = ['alex','wusir','yuanhao','linhaifeng','henry']
def inner(name):
if len(name) == 0:
return '没有找到路'
res = lis.pop(0)
if res == 'henry':
return '%s说:我知道老男孩就在沙河地铁站附近'%res
print('hi美男%s敢问路在何方'%res)
print('%s回答道,我也不知道,我帮你问问%s'%(res,lis))
f = inner(lis)
return f
print(inner(lis))
六、人狗大战
import random
import time
class Person:
def __init__(self,name,hp,ad,sex):
self.name = name
self.ad = ad
self.hp = hp
self.sex = sex
def da(self,dog):
yy = random.randint(1,self.ad)
dog.hp -= yy
print('%s使用%s,打了%s,%s掉了%s点血'%(self.name,arms.name,dog.name,dog.name,yy))
if dog.hp < 50:
print("{}使用终极必杀技{}".format(dog.name,arms.skill()))
class Dog:
def __init__(self,name,hp,ad,kind):
self.name = name
self.hp = hp
self.ad = ad
self.kind = kind
def yao(self,person):
uu = random.randint(1,self.ad)
person.hp -= uu
print('%s咬了%s,%s掉了%s点血' % (self.name, person.name, person.name,uu))
if person.hp < 50:
print("{}使用终极必杀技{}".format(person.name,arms.skill()))
class Arms:
def __init__(self,name,hp,ad):
self.name = name
self.hp = hp
self.ad = ad
def skill(self):
li = ['飞龙在天','乾坤大挪移','九阳神功']
f = random.choice(li)
return f
arms = Arms('铁锹',3000,2000)
henry = Person('henry',500,30,'男')
dog = Dog('大黄',300,30,'哈士奇')
c = 1
while dog.hp > 0:
print('第{}回合'.format(c))
dog.yao(henry)
henry.da(dog)
time.sleep(1)
c +=1
七、计算器
import re
express = '1-2*((60-30+(9-2*5/3+7/3*99/4*2998+10*568/14)*(-40/5))-(-4*3)/(16-3*2))'
express = express.replace(' ','')
def cout(exp):
if '*' in exp:
a,b = exp.split('*')
return str(float(a) * float(b))
else:
a, b = exp.split('/')
return str(float(a) / float(b))
def format_exp(exp):
exp = exp.replace('++','+')
exp = exp.replace('+-','-')
exp = exp.replace('--','+')
exp = exp.replace('-+','-')
return exp
def cal_no(res):
while True:
chengshu = re.search('\d+\.?\d*[*/]-?\d+\.?\d*', res)
if chengshu:
ret = chengshu.group()
resut = cout(ret)
res = res.replace(ret, resut)
else:break
print(res)
res1 = format_exp(res)
res_lis = re.findall('[-+]?\d+(?:\.\d+)?',res1)
print(res_lis)
sum_n = 0
for i in res_lis:
sum_n += float(i)
return sum_n
def remove_bracket(express):
while True:
exp = re.search('\([^()]+\)',express)
if exp:
res = exp.group()
rep = cal_no(res)
print(rep)
express = express.replace(res,str(rep))
print(express)
else:break
return express
ret = remove_bracket(express)
print(cal_no(re
八、校验文件的一致性
九、打印九九乘法表
for i in range(1,10):
for j in range(1,i+1):
print("%s*%s=%s"%(i,j,i*j),end=' ')
print()
for i in range(1,10):
for j in range(i,10):
print("%s*%s=%s"%(i,j,i*j),end=' ')
print()
十、购物车作业
goods = []
money = input('请充值充值金额').strip()
with open('商品信息',encoding='utf-8')as f:
for i in f:
xinxi = i.strip().split(' ')
if xinxi[0] == 'name':
continue
else:
dic = dict([('name',xinxi[0]),('price',xinxi[1])])
goods.append(dic)
print(goods)
"""
页面显示 序号 + 商品名称 + 商品价格
"""
a = 1
for v in goods:
print(a,v['name'],v['price'])
a += 1
print('n 购物车结算')
print('q 或 Q 退出')
shop_dic = {}
sum = 0
a = 1
dic = {}
balance = 0
while 1:
shuru = input('请输入序号').strip()
if shuru.isdigit() and (0 < int(shuru) <= len(goods)):
print(goods[int(shuru)-1]['name'],goods[int(shuru)-1]['price'])
shop_dic.setdefault(goods[int(shuru)-1]['name'],{'price':goods[int(shuru)-1]['price'],'amount':0})
shop_dic[goods[int(shuru)-1]['name']]['amount'] += 1
elif shuru == 'n':
for k,j in shop_dic.items():
print(a,k,j['price'],j['amount'])
dic[a] = k
a += 1
sum += int(j['price'])*int(j['amount'])
if int(money) >= sum:
print('结算成功')
balance = int(money)-sum
for s, b in shop_dic.items():
print(s, b['price'], b['amount'])
print('共计消费{}元,剩余金额{}元'.format(sum, balance))
break
while int(money) < sum:
print('余额不足')
shanchu = input('请输入要删除的商品序号')
shop_dic[dic[int(shanchu)]]['amount'] -= 1
sum = sum - int(shop_dic[dic[int(shanchu)]]['price'])
else:
print('结算成功')
balance = int(money) - sum
for s, b in shop_dic.items():
print(s, b['price'], b['amount'])
print('共计消费{}元,剩余金额{}元'.format(sum, balance))
break
elif shuru.upper() == 'Q':
print('程序退出')
break
else:
print('输入有误请重新输入')
with open('购买账单',encoding='utf-8',mode='w') as f1:
for s, b in shop_dic.items():
f1.write('商品名称:{} '.format(s))
f1.write('单价:{} '.format(b['price']))
f1.write('数量:{}\n'.format(str(b['amount'])))
f1.write('共计消费{}元\n'.format(sum))
f1.write('剩余金额%s元'%(balance))
十一、博客园登录
import time
dic = {
1: '请登录',
2: '请注册',
3: '文章页面',
4: '日记页面',
5: '评论页面',
6: '收藏页面',
7: '退出程序',
}
def Home_display():
"""
首页展示
:return:
"""
print('欢迎来到博客园首页!!!')
for i in dic:
print(i,dic[i])
Home_display()
def ster():
"""
用户注册函数,将用户名,密码写入文件
:return:
"""
user_name = input('请填写注册名称').strip()
pass_word = input('请填写注册密码').strip()
with open('register','a+',encoding='utf-8') as f1:
f1.write('{},{}'.format(user_name,pass_word)+'\n')
print('注册成功,请登录!!!')
def login_system():
"""
登录函数
:return:
"""
user_name = []
time = 3
with open('register', 'r+', encoding='utf-8') as f:
for i in f:
user_name.append(i.strip())
while time >= 1:
name = input('请输入用户名')
wd = input('请输入密码')
l = name + ',' + wd
if l in user_name:
print('登录成功')
chioce(name)
else:
time -= 1
if time == 0:
print('登录次数超出限制,请您注册后登录!')
break
print('用户名或密码错误,剩余{}次机会'.format(time))
def eixt_procedure():
"""
退出程序
:return:
"""
print('程序退出,欢迎下次光临')
exit()
def log(n,func):
with open('log','a+',encoding='utf-8') as f2:
current_time = time.strftime("%Y-%m-%d-%X",time.localtime())
f2.write('{}:{}调用了{}函数'.format(n,current_time,func) + '\n')
def diary(n):
"""
日记页面
:return:
"""
print('欢迎{}访问日记页面'.format(n))
log(n, 'diary')
def comment(n):
"""
评论页面
:return:
"""
print('欢迎{}访问评论页面'.format(n))
log(n, 'comment')
def Collection(n):
"""
收藏页面
:return:
"""
print('欢迎{}访问收藏页面'.format(n))
log(n, 'Collection')
def Article(n):
"""
文章页面
:return:
"""
print('欢迎{}访问文章页面'.format(n))
log(n, 'Article')
lis = [login_system,ster,Article,diary,comment,Collection,eixt_procedure,log]
def chioce(a):
"""
用户选择函数
:return:
"""
while 1:
number = input('请选择页面:').strip()
if number.isdigit() and 3 <= int(number) <= 6:
lis[int(number)-1](a)
elif number.isdigit() and (int(number) ==1 or int(number)==7):
if int(number)==7:
eixt_procedure()
lis[int(number) - 1]()
else:
print('请输入正确页面选项:')
def chioce1():
while 1:
number = input('请选择登录或注册或退出').strip()
if number.isdigit() and (1 == int(number) or int(number) == 7 or int(number) == 2) :
if int(number) == 7:
eixt_procedure()
else:
lis[int(number)-1]()
else:
print('输入有误请重新输入')
chioce1()
十二、学生选课系统
import hashlib
import pickle
import os
import logging
logger = logging.getLogger()
fh = logging.FileHandler('test.log',encoding='utf-8')
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)
logger.setLevel(logging.DEBUG)
def md5_user(username,password):
md5 = hashlib.md5(username.encode('utf-8'))
md5.update(password.encode('utf-8'))
return md5.hexdigest()
def read_file_name(file_name):
with open(file_name,'rb') as f:
while True:
try:
res = pickle.load(f)
if res:
yield res
except EOFError:
break
def add_file(file_name,content):
with open(file_name,'ab') as f:
pickle.dump(content,f)
class Course:
def __init__(self,name,price,period,teacher):
self.name = name
self.price = price
self.period = period
self.teacher = teacher
def __str__(self):
return format('\t课程:' + self.name,'<13') + format('价钱:' + self.price,'<13') + format('周期:' + self.period,'<13') + format('老师:' + self.teacher,'<13')
class Admin:
msg = [('创建课程', 'course'),
('创建学生和学生账号', 'account_num'),
('查看所有课程', 'view_courses'),
('查看所有学生', 'look_all_student'),
('查看所有学生的选课情况', 'look_all_courses'),
('退出程序', 'quit')]
def __init__(self,username,password,identify='Admin'):
self.username = username
self.password = password
self.identify = identify
def course(self):
student_name = input('请输入课程名称')
student_pricce = input('请输入课程价钱')
student_period = input('请输入课程周期')
student_teacher = input('请输入授课老师')
Course1 = Course(student_name,student_pricce,student_period,student_teacher)
add_file('course_file', Course1)
return True
def account_num(self):
username = input('请输入要创建的姓名')
password = input('请输入要创建的密码')
student1 = Student(username,md5_user(username,password))
add_file('vip_admin', student1)
return True
def view_courses(self):
ret = read_file_name('course_file')
for index,i in enumerate(ret,1):
print(index,i)
return True
def look_all_student(self):
ret = read_file_name('vip_admin')
for i in ret:
if i.identify == 'Student':
print(i.username,i.password)
return True
def look_all_courses(self):
ret = read_file_name('vip_admin')
for i in ret:
if i.identify == 'Student':
print(i.username)
for j in i.course:
print(j)
return True
def quit(self):
print('程序退出')
logger.info(self.username + '——' + self.msg[-1][0])
exit()
class Student:
msg = [('查看所有课程', 'look_all_course'),
('选择课程', 'choice_course'),
('查看所选课程', 'look_choice_course'),
('退出程序', 'quit')]
def __init__(self,username,password,identify = 'Student'):
self.username = username
self.password = password
self.identify = identify
self.course = []
def look_all_course(self):
ret = read_file_name('course_file')
for index, i in enumerate(ret, 1):
print(index, i)
return True
def choice_course(self):
ret = list(read_file_name('course_file'))
for index, i in enumerate(ret, 1):
print(index, i)
while True:
choice = input('请选择课程>>>:').strip()
if choice.isdigit() and int(choice) in range(1,len(ret) +1 ):
print(ret[int(choice)-1].name)
print([i.name for i in self.course])
if ret[int(choice)-1].name not in [i.name for i in self.course]:
self.course.append(ret[int(choice)-1])
with open('vip_admin','rb') as f1,open('vip_admin2','wb') as f2:
while True:
try:
res1 = pickle.load(f1)
if res1.username == self.username:
res1.course.append(ret[int(choice)-1])
pickle.dump(res1,f2)
else:
pickle.dump(res1, f2)
except EOFError:break
os.remove('vip_admin')
os.rename('vip_admin2','vip_admin')
logger.info(self.username + '——' + self.msg[1][0]+ str(ret[int(choice)-1]))
break
else:
print('该课程您已选择')
break
else:
print('输入有误重新输入')
def look_choice_course(self):
ret = read_file_name('vip_admin')
for i in ret:
if i.username == self.username:
for j in i.course:
print(j)
return True
def quit(self):
logger.info(self.username + '——' + self.msg[-1][0])
exit()
def login(username,password):
ret = read_file_name('vip_admin')
for i in ret:
if i.username == username and i.password == md5_user(username,password):
return i
else:return False
def auth():
lis = ['登录','退出']
while True:
for index,opt in enumerate(lis,1):
print(index,opt)
num = input('请输入你要操作的内容')
if num.isdigit() and int(num) in range(1,len(lis)+1):
if num == '1':
username = input('请输入用户名')
password = input('请输入密码')
ret = login(username,password)
if ret:
print('登录成功')
logger.info(username + '——' + '登录成功')
return ret
else:
print('登录失败')
elif num == '2':
exit()
else:
print('您输入的序号有误请重新输入')
def main():
ret = auth()
if ret:
obj = ret
while True:
for index,i in enumerate(obj.msg,1):
print(index,i[0])
choice = input('请选择序号')
if choice.isdigit() and int(choice) in range(1,len(obj.msg) + 1):
if hasattr(obj,obj.msg[int(choice) - 1][1]):
if callable(getattr(obj,obj.msg[int(choice) - 1][1])):
ret = getattr(obj, obj.msg[int(choice) - 1][1])()
if ret:
logger.info(obj.username+'——'+obj.msg[int(choice) - 1][0])
else:
print('您输入的序号有误,请重新输入')
main()