【发布时间】:2019-02-09 11:19:41
【问题描述】:
我正在尝试测试一些游戏策略,可以由 10 个非负整数加起来为 100 来定义。有 109 个选择 9,或者大约 10^12 个,所以比较它们不是实际的。我想随机抽取大约 1,000,000 个样本。
我已经尝试过the answers to this question、and this one 中的方法,但似乎都太慢了,无法工作。最快的方法在我的机器上似乎需要大约 180 小时。
这就是我尝试制作生成器的方式(改编自之前的 SE 答案)。出于某种原因,更改prob 似乎不会影响将其转换为列表的运行时间。
def tuples_sum_sample(nbval,total, prob, order=True) :
"""
Generate all the tuples L of nbval positive or nul integer
such that sum(L)=total.
The tuples may be ordered (decreasing order) or not
"""
if nbval == 0 and total == 0 : yield tuple() ; raise StopIteration
if nbval == 1 : yield (total,) ; raise StopIteration
if total==0 : yield (0,)*nbval ; raise StopIteration
for start in range(total,0,-1) :
for qu in tuples_sum(nbval-1,total-start) :
if qu[0]<=start :
sol=(start,)+qu
if order :
if random.random() <prob:
yield sol
else :
l=set()
for p in permutations(sol,len(sol)) :
if p not in l :
l.add(p)
if random.random()<prob:
yield p
拒绝采样似乎需要大约 300 万年,所以这也结束了。
randsample = []
while len(randsample)<1000000:
x = (random.randint(0,100),random.randint(0,100),random.randint(0,100),random.randint(0,100),random.randint(0,100),random.randint(0,100),random.randint(0,100),random.randint(0,100),random.randint(0,100),random.randint(0,100))
if sum(x) == 100:
randsample.append(x)
randsample
谁能想到另一种方法来做到这一点?
谢谢
【问题讨论】:
-
分号...在python中...天哪。说真的,您的代码很难遵循。您没有遵循样式约定,也没有使用描述性很强的变量名称。
l是您可以使用的最差变量名称的经典示例。使用类似found_set -
@FHTMitchell 感谢您的反馈,仍然是初学者。代码大多是从别处偷来的,不管怎样。
-
你试过this method吗?
-
@glibdud 我刚试过,效果很好,类似于下面 Eric Duminil 的回答。