相关疑难解决方法(0)

random.choice的加权版本

我需要编写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)

python optimization

209
推荐指数
11
解决办法
14万
查看次数

加权选择简短

如果我在列表中有一组项目.我想根据另一个权重列表从该列表中进行选择.

例如我的收藏是['one', 'two', 'three']和权重[0.2, 0.3, 0.5],我希望这个方法在所有抽奖的大约一半中给我'三'.

最简单的方法是什么?

python numpy

46
推荐指数
4
解决办法
4万
查看次数

Pythonic方式选择具有不同概率的列表元素

import random
pos = ["A", "B", "C"]
x = random.choice["A", "B", "C"]
Run Code Online (Sandbox Code Playgroud)

这段代码给了我"A","B"或"C"的概率相等.当你想要30%的"A",40%的"B"和30%概率的"C"时,是否有一种很好的表达方式?

python

35
推荐指数
5
解决办法
4万
查看次数

Python中的概率分布

我有一堆钥匙,每个钥匙都有一个不可靠的变量.我想随机选择其中一个键,但我希望它不太可能被选中(键,值)而不是不太可能(更可能)的对象.我想知道你是否会有任何建议,最好是我可以使用的现有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)

python random algorithm distribution probability

21
推荐指数
2
解决办法
2万
查看次数

如何根据加权概率从python字典中选择键?

我有一个Python字典,其中键表示一些项目,值表示所述项目的一些(标准化)加权.例如:

d = {'a': 0.0625, 'c': 0.625, 'b': 0.3125}
# Note that sum([v for k,v in d.iteritems()]) == 1 for all `d`
Run Code Online (Sandbox Code Playgroud)

鉴于项目与权重的这种相关性,我如何选择一个关键字,d结果为'a'的时间为6.25%,结果为'b'的时间为32.25%,结果的62.5%为'c' "?

python random probability

7
推荐指数
3
解决办法
5426
查看次数