ropon
2018-10-15 22:26:51 +08:00
整理思路如下:
#算法一
#################################################################
def hongbao(amount=5, count=3):
s = []
min = 1 #分
amount = amount * 100 #单位分
max = amount - (count-1) #单位分
for i in range(count-1):
# num = random.randint(0, amount)
num = random.uniform(0, int(amount))
while num < min or num > max:
num = random.uniform(0, int(amount))
amount -= num
s.append(round((num / 100), 2))
s.append(round((amount / 100), 2))
random.shuffle(s)
return s
print(hongbao(1, 6))
##############################################################
算法二
#############################################################
# 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)