Python 发红包算法

#算法一
思路

sum =0
amount=500分 count=4个人抢 
1 - 500-(4-1-0) -0  i = 0
1. 1 - 1-497 num = 400
sum = sum + num 0+400
1 - 500-(4-1-1) -400
2. 1 - 82 num = 50
sum = sum + num 400 +50
1- 500 -(4-1-2) -450
3. 1 - 49 num =49
sum = sum+49=491
amount -sum 1 / 100
def hongbao(amount=5, count=3):
    s = []
    sum = 0 #分
    amount = amount * 100 #单位分
    for i in range(count-1): #0 1 2
        max = amount -sum - (count - 1 - i)  # 单位分 500-(3-1-0)=498
        num = random.randint(1, max) #1,498 400
        s.append((num / 100))
        sum = sum + num
    s.append((amount - sum) / 100)
    random.shuffle(s)
    return s

print(hongbao(5, 4))

算法二

# 0--|----|--------|-----------|-------20
# 0  2    4        10          16      20
def hongbao(amount=10, count=5):
    ret = random.sample(range(1, amount * 100), count - 1) #分为单位
    ret.extend([0, amount * 100]) #追加多个值0 amount * 100
    ret.sort() #排序
    # return [((ret[i+1] - ret[i]) / 100 for i in range(num))] # 列表生产式
    for i in range(count):
        yield (ret[i+1] - ret[i]) / 100

res = hongbao(10, 6)
for i in res:
    print(i)

转载于Ropon博客https://www.idiyrom.com/252.html

你可能感兴趣的:(经验分享)