用python实现红包机制

方法一,逻辑是后一个红包的范围是[0.01,剩下的钱*2/剩下的红包数,如果最后钱不足分配给每个人,就把后几个每人分配0.01元。

主要思想就是,每个人至少能领取到0.01元.

import random

def func(total,count):
    money = 0
    total = round(total,2)
    for i in range(count,0,-1):
        total = total - money  #后一个红包的范围是[0.01,剩下的钱*2/剩下的红包数]
        money = round(random.uniform(0.01,((2*total)/i)),2)
        if total <= 0.01*(i-1):  #保证最后i-1人能够得到0.01元
            print(round(total + money - (0.01*(i-1))))
            for j in range(i-1):
                print(0.01)
            break
        else:
            print(money)
func(100,10)

 方法二,

import random
def red_packet(money,num):
    money = money * 100
    ret = random.sample(range(1,money),num-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(200,10)
for money in ret_g:
    print(money)
原文地址:https://www.cnblogs.com/cuiyuanzhang/p/9508155.html