我需要编写random.choice的加权版本(列表中的每个元素都有不同的被选中概率).这就是我想出的:
def weightedChoice(choices):
"""Like random.choice, but each element can have a different chance of
being selected.
choices can be any iterable containing iterables with two items each.
Technically, they can have more than two items, the rest will just be
ignored. The first item is the thing being chosen, the second item is
its weight. The weights can be any numeric values, what matters is the
relative differences between them.
"""
space = {}
current = 0
for choice, weight …Run Code Online (Sandbox Code Playgroud) 我有一个字典,其中每个键都有一个可变长度列表,例如:
d = {
'a': [1, 3, 2],
'b': [6],
'c': [0, 0]
}
Run Code Online (Sandbox Code Playgroud)
是否有一种干净的方法来获取随机字典键,按其值的长度加权?
random.choice(d.keys())将对键进行相同的加权,但在上面的情况下,我希望'a'大约一半的时间返回.
我有一堆钥匙,每个钥匙都有一个不可靠的变量.我想随机选择其中一个键,但我希望它不太可能被选中(键,值)而不是不太可能(更可能)的对象.我想知道你是否会有任何建议,最好是我可以使用的现有python模块,否则我需要自己制作.
我检查了随机模块; 它似乎没有提供这个.
我必须为1000个不同的对象集做出数百万次这样的选择,每个对象包含2,455个对象.每个集合将在彼此之间交换对象,因此随机选择器需要是动态的.拥有1000套2,433件物品,即243.3万件物品; 低内存消耗至关重要.由于这些选择不是算法的主要部分,我需要这个过程非常快; CPU时间有限.
谢谢
更新:
好的,我试图明智地考虑你的建议,但时间是如此有限......
我查看了二叉搜索树方法,它看起来风险太大(复杂而复杂).其他建议都类似于ActiveState配方.我拿了它并稍微修改了一下,希望提高效率:
def windex(dict, sum, max):
'''an attempt to make a random.choose() function that makes
weighted choices accepts a dictionary with the item_key and
certainty_value as a pair like:
>>> x = [('one', 20), ('two', 2), ('three', 50)], the
maximum certainty value (max) and the sum of all certainties.'''
n = random.uniform(0, 1)
sum = max*len(list)-sum
for key, certainty in dict.iteritems():
weight = float(max-certainty)/sum
if n < weight:
break
n = n …Run Code Online (Sandbox Code Playgroud) 该random模块(http://docs.python.org/2/library/random.html)具有几个固定的函数来随机抽样.例如,random.gauss将使用给定的均值和西格玛值对具有正态分布的随机点进行采样.
我正在寻找一种方法来提取一些N用我自己的分布的给定区间之间随机样本尽可能快地在python.这就是我的意思:
def my_dist(x):
# Some distribution, assume c1,c2,c3 and c4 are known.
f = c1*exp(-((x-c2)**c3)/c4)
return f
# Draw N random samples from my distribution between given limits a,b.
N = 1000
N_rand_samples = ran_func_sample(my_dist, a, b, N)
Run Code Online (Sandbox Code Playgroud)
这里ran_func_sample是我后和a, b是从中可以得出样本的限制.有那种东西python吗?
你能告诉我任何产生非均匀随机数的方法吗?
我正在使用Java,但代码示例可以是您想要的任何内容.
一种方法是通过将两个均匀随机数加在一起(即滚动2个骰子)来创建偏斜分布.
我需要一种简单的方法来随机选择字母表中的一个字母,加权我希望它出现的百分比.例如,我希望字母'E'在5.9%的时间内出现在随机函数中,但我只希望'Z'在0.3%的时间内出现(依此类推,基于每个的平均出现次数)字母表中的字母).有什么建议?我看到的唯一方法是使用10000个字母(590'E',3'Z'等)填充数组,然后从该数组中随机选择一个字母,但它看起来像内存密集且笨拙.
random ×5
python ×4
algorithm ×1
dictionary ×1
distribution ×1
objective-c ×1
optimization ×1
performance ×1
probability ×1