day 05 模块
time,os,sys,random,re,正则。前面几个还听懂了,到re和正则,我感觉整个人在放空,不知道老师在干啥。作业挺难的,时间模块还好,random发红包,re计算器,计算器愣是自己对着女神视频,又弄了一周才弄明白。附上计算器代码:
import re def deal_with(s): if '-+' in s: s = s.replace('-+','-') #print(s) if '+-' in s: s = s.replace('+-','-') #print(s) if '--' in s: s = s.replace('--','+') #print(s) if '++' in s: s = s.replace('++','+') #print(s) return s def mul_div(exp): #定义了一个乘除法 if '*' in exp: exp = exp.strip('()') a,b = exp.split('*') c = float(a) * float(b) return str(c) elif '/' in exp: exp = exp.strip('()') a,b = exp.split('/') #print(a,b) c = float(a) / float(b) return str(c) def calculate(exp): #计算带括号的最小子式 while 1: res = re.search('\d+\.?\d*[*/]-?\d+\.?\d*',exp)#匹配乘除法 if res: res = res.group().strip() ret = mul_div(res) #用定义好的乘除函数计算 #print(ret) exp = exp.replace(res, ret, 1) #print(exp) else:break #算完该括号内所有乘除法 exp = deal_with(exp) #在计算加减之间,先做处理 l = re.findall('[+-]?\d+\.?\d*',exp) #用findall,匹配带正负号的所有数字,这样更好算.不用乘除的那种方法 sum = 0 for i in l : i = float(i) #字符串转数字 sum += i #求和 #print(sum) return str(sum) #就是该括号内式子的值了,返回字符串类型 def core(s): s = s.replace(' ', '') while 1: exp = re.search(r'\([^()]+\)', s) #先匹配最里层带括号的 if exp: exp = exp.group() print(exp) res = calculate(exp.strip('()')) #计算括号内式子的值 print(res) s = s.replace(exp,res,1) #将结果替换回原式 print(s) else: #所有括号都去完了 result = calculate(s) #再单独算一次 break return result s = ' 1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )' #s = '(60-30 -8 * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 ))' a = core(s) print(a) print(eval(s))
一开始就弄一个庞然大物,这是我很讨厌学校设置的地方,容易产生畏难情绪.而且复杂的东西也是由简单的东西一步步拆开的嘛.上来弄得这么复杂,是要干啥.算了,不吐槽了.函数和递归,熟悉了一下.
首先当然是正则的书写,
红包那个也还值得一提
'''开哥的思路,感觉更简洁''' def kaige(total_money,n): import random l = range(1,total_money * 100) money =[] s = random.sample(l,n - 1) s.append(total_money * 100)#分别在一头一尾插入0和红包总金额 s.insert(0,0) s.sort() #排序 # print(s) # print(len(s)) for i in range(len(s)-1):#这里得len-1,因为加了加了一头一尾 m = float(s[i + 1] - s[i])/100 money.append(m) print('红包已抢完!记录如下:') print(money) best = max(money) #手气最好 number = money.index(best) print('第%s个人手气最好,抢到了%s元'%(number + 1,best)) kaige(200,5)
思路很巧妙,回过去发现,不少题值得一提,下面这个是6位验证码,刚刚看的时候已经记不得了。
def v_code(n=6): #定义验证码函数,位数默认为6 import random s = '' for i in range(n):#循环n次 lower = random.choice([chr(random.randint(97,122))])#随机生成小写 upper = random.choice([chr(random.randint(65,90))])#随机生成大写 num = str(random.randint(0,9)) #随机生成一个0-9之间的整数 choice = random.choice([lower,upper,num])#随机从上面3个中选一个 s += choice return s print(v_code())

浙公网安备 33010602011771号