Python的十二道编程题,码住战胜一切
Posted sakttylls
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python的十二道编程题,码住战胜一切相关的知识,希望对你有一定的参考价值。
一、计算文件大小
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))
找到路后会把结果返回给上一个调用者’linhaifeng’
‘linhaifeng’会把结果返回给上一个调用者’yuanhao’…
最终会把结果返回给最开始的调用者inner
六、人狗大战
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) # (9-2*5/3+7/3*99/4*2998+10*568/14)
if chengshu:
ret = chengshu.group() # 2*5
resut = cout(ret) # 得到乘除法的计算结果 10.0
# 将2*5替换成10.0
res = res.replace(ret, resut) # (9-10.0/3+7/3*99/4*2998+10*568/14)
else:break
print(res) # (9-3.3333333333333335+173134.50000000003+405.7142857142857)
# 表达式的符号管理把++变成+,--变成-,+-变成-,-+变成-
res1 = format_exp(res) # 将替换后的结果从新赋值给res
# 将括号内的加减法都匹配出来
res_lis = re.findall('[-+]?\\d+(?:\\.\\d+)?',res1)
print(res_lis) # ['9', '-3.3333333333333335', '+173134.50000000003', '+405.7142857142857']
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() # (9-2*5/3+7/3*99/4*2998+10*568/14)
rep = cal_no(res) # 173545.88095238098
print(rep)
express = express.replace(res,str(rep)) # 因为rep的结果是一个数字
print(express) # 1-2*((60-30+173545.88095238098*(-40/5))-(-4*3)/(16-3*2))
else:break
return express # 括号内的表达式全部计算完成1-2*-1388338.2476190478
ret = remove_bracket(express)
print(cal_no(re
八、校验文件的一致性
# import os
# import hashlib
# def file_md5(path):
# filesize = os.path.getsize(path)
# md5 = hashlib.md5()
# with open(path,'rb') as f:
# while filesize >= 4096:
# content = f.read(4096)
# md5.update(content)
# filesize -= 4096
# else:
# content = f.read(filesize)
# if content:
# md5.update(content)
# return md5.hexdigest()
#
# def cmp_file(path1,path2):
# return file_md5(path1) == file_md5(path2)
# path1 = r'D:\\s20\\day18\\视频\\4.面向对象整理.mp4'
# path2 = r'D:\\s20\\day18\\视频\\tmp.mp4'
# ret = cmp_file(path1,path2)
# print(ret)
九、打印九九乘法表
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()
十、购物车作业
创建一个名为‘购买账单的txt文件
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():
# python学习交流群:309488165
# 展示购物车商品名称价格数量
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以上是关于Python的十二道编程题,码住战胜一切的主要内容,如果未能解决你的问题,请参考以下文章
今日头条 2018 AI Camp 6 月 2 日在线笔试编程题第二道——两数差的和