【发布时间】:2018-07-08 18:27:59
【问题描述】:
我有一个加权随机状态函数,它采用有限数量的相对权重并根据伪随机选择输出一个整数。但是,我想让函数可扩展以处理 n 个状态/权重。什么是重写这个函数的优雅方法,它可以将 *args 作为输入?
编辑:由于这些权重是相互关联的,所以对我来说棘手的部分是考虑使 elif 逻辑可扩展的最佳方法。
def weighted_random(weight1, weight2, weight3, weight4, weight5, weight6, weight7, weight8):
totalWeight = weight1 + weight2 + weight3 + weight4 + weight5 + weight6 + weight7 + weight8
randomInt = random.randint(1, totalWeight)
if randomInt <= weight1:
return 0
elif randomInt > weight1 and randomInt <= (weight1 + weight2):
return 1
elif randomInt > (weight1 + weight2) and randomInt <= (weight1 + weight2 + weight3):
return 2
elif randomInt > (weight1 + weight2 + weight3) and randomInt <= (weight1 + weight2 + weight3 + weight4):
return 3
elif randomInt > (weight1 + weight2 + weight3 + weight4) and randomInt <= (weight1 + weight2 + weight3 + weight4 + weight5):
return 4
elif randomInt > (weight1 + weight2 + weight3 + weight4 + weight5) and randomInt <= (weight1 + weight2 + weight3 + weight4 + weight5 + weight6):
return 5
elif randomInt > (weight1 + weight2 + weight3 + weight4 + weight5 + weight6) and randomInt <= (weight1 + weight2 + weight3 + weight4 + weight5 + weight6 + weight7):
return 6
elif randomInt > (weight1 + weight2 + weight3 + weight4 + weight5 + weight6 + weight7):
return 7
else:
return("error")
【问题讨论】:
-
您的权重是否假定为排序整数?
-
@dawg 我认为它们是整数,但没有排序。像
weighted_random(5, 1, 4)这样的东西会给你 50% 的命中索引 0、索引 1 的 10% 和索引 2 的 40%。 -
@fafl:它的计算方式在数学上不支持这一点。
-
@dawg 嗯,我觉得不错。你有一个不起作用的例子吗?