假设红包金额为money,数量是num,并且红包金额money>=num*0.01
原理如下,从1~money*100的数的集合中,随机抽取num-1个数,然后对这些数进行排序,在排序后的集合前后分别插入0和money*100,组成新的集合
用新的集合,(后一个数-前一个数)/100得到红包的大小
然后使用红包的时候,从num个红包集合中随机拿一个,既是随机红包了
def redbags(money, num=10): import random choice = random.sample(range(1, money * 100), num - 1) choice.extend([0,money*100]) choice.sort() return [(choice[i + 1] - choice[i]) / 100 for i in range(num)] |
#!/usr/bin/env python # -*-coding:utf-8 -*- import random dic={} lis = ['KeLan','Monkey','Dexter','Superman','Iron Man','Robin'] def redpacket(cash,person,index): if cash>0 and person !=1: n = round(random.uniform(0.01,cash-(0.01*person)),2) dic[lis[index]] = n print str(n).ljust(4,"0") person-=1 cash-=n index+=1 redpacket(cash,person,index) else: dic[lis[index]]=round(cash,2) print str(cash).ljust(4,"0") redpacket(10,len(lis),0) print dic print "手气最佳:",max(dic.items(),key=lambda x:x[1]) |