首页 技术 正文
技术 2022年11月15日
0 收藏 479 点赞 4,064 浏览 1534 个字

用Python编写简单的发红包程序:

第一种解法:数轴方法解决

import random
def red_packet(money,num):
money = money * 100 #将钱数转换成分为单位
ret = random.sample(range(1,money),num-1) #在最低钱数1分与总钱数之间生成人数减1个数作为数轴的节点
ret.sort() #对列表进行排序
ret.insert(0,0)
ret.append(money)
for i in range(len(ret)-1):
yield (ret[i+1]-ret[i])/100
ret_g = red_packet(100,10)
for money in ret_g:
print(money)

第二种解法:用概率解决

def red_packet(money,person):
dic_person_money = {}
for i in range(person):
num = random.randint(1,100)
dic_person_money['Person%s' % (i+1)] = num
num_sum = 0
for i in dic_person_money:
num_sum += dic_person_money[i]
for i in dic_person_money:
x = round(dic_person_money[i]/num_sum*money,2)
dic_person_money[i] = '$%s' % x
return dic_person_money
result = red_packet(1,10)
print(result)

用Python设计一个简单的计算器:

import re
def atom_cal(exp):
if '*' in exp:
a,b = exp.split('*')
return str(float(a)*float(b))
elif '/' in exp:
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 expdef mul_div(exp):
while 1:
ret = re.search('\d+(\.\d+)?[*/]-?\d+(\.\d+)?',exp)
if ret:
atom_exp = ret.group()
res = atom_cal(atom_exp)
exp = exp.replace(atom_exp,res)
else:return expdef add_sub(exp):
ret = re.findall('[+-]?\d+(?:\.\d+)?',exp)
sum = 0
for i in ret:
sum += float(i)
return sumdef cal(exp):
exp = mul_div(exp)
exp = format_exp(exp)
return add_sub(exp)def main(exp):
exp = exp.replace(' ','')
while 1:
ret = re.search('\([^()]+\)',exp)
if ret:
cal_exp = ret.group()
res = str(cal(cal_exp))
exp = exp.replace(cal_exp,res)
else:break
return cal(exp)
s = '1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )'
print(main(s))
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,918
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,444
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,255
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,069
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,701
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,741