该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
import random
class RedPacket:
def __init__(self, money):
self.money = money
def similar_packet(self, n):
print('随机抢红包······')
# 先获取 n-1 个,最后一个用来补数
hongbao_list = [self.shuiji(n) for x in range(n-1)]
# 如果 n-1 个的总金额超过了就重新获取
while sum(hongbao_list) >= self.money:
hongbao_list = [self.shuiji(n) for x in range(n-1)]
# 补位的最后金额,随机插入
hongbao_list.insert(int(random.randint(0,n)),self.money - sum(hongbao_list))
count = 1
# 自己看一下总金额对不对,可以删除
print('实际金额',sum(hongbao_list))
while count <= n:
if count < n:
print("第[%s]个人抢红包金额是%0.2f元" % (count, hongbao_list.pop()))
else:
print("第[%s]个人抢红包金额是%0.2f元" % (count, hongbao_list.pop()))
count += 1
# 随机生成模块
def shuiji(self,n):
# (总金额/(红包数+(-20%~50%浮动))+(随机几分钱))然后取2位小数,这里红包个数越多平均额度越低,红包个数波动造成额度波动
return round((self.money / (n + random.randint(-(n*0.2), n*0.5))) + round(random.random(), 2), 2)
rp = RedPacket(100)
rp.similar_packet(10)