This topic created in 2781 days ago, the information mentioned may be changed or developed.
比如 100 元红包 10 个人抢,以下算法:先随机生成 10 个数,之和等于红包金额,然后依次从这个列表随机取一个
,取了后移除,在随机取一个,这样算法是否合理,公平不呢
def hongbao(amount=5, count=3):
s = []
sum = 0
min = 0.01
max = float(amount) - count * 0.01
num = 0
for i in range(count-1):
num = round(random.uniform(0, float(amount) - sum), 2)
while num < min or num > max:
num = round(random.uniform(0, float(amount) - sum), 2)
sum += num
s.append(num)
s.append(round(float(amount) - sum, 2))
# return s
for i in range(count):
temp = random.choice(s)
print("第{0}个人抢的红包是{1}".format(i + 1, temp))
s.remove(temp)
hongbao(100, 10)
测试有问题,问题在哪里呢
Supplement 1 · Oct 15, 2018
def hongbao(amount=5, count=3):
s = []
sum = 0
min = 0.01
max = float(amount) - (count-1) * 0.01
for i in range(count-1):
num = round(random.uniform(0, float(amount) - sum), 2)
while num < min or num > max:
num = round(random.uniform(0, float(amount) - sum), 2)
sum += num
s.append(num)
s.append(round(float(amount) - sum, 2))
# return s
for i in range(count):
temp = random.choice(s)
print("第{0}个人抢的红包是{1}".format(i + 1, temp))
s.remove(temp)
hongbao(100, 10)
5 replies • 2018-10-15 22:26:51 +08:00
 |
|
2
crab Oct 15, 2018
二倍均值法
|
 |
|
4
beny2mor Oct 15, 2018
我看了下那些 stackoverflow 的回复, 最简单的是生成 10 个随机数,然后按照比例来分 100 元
|
 |
|
5
ropon Oct 15, 2018
整理思路如下:
#算法一 ################################################################# 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)
|