[Python-ideas] [Python Ideas] Random weighted choice idea to add to random lib

Steven Basart xksteven at uchicago.edu
Wed Mar 23 10:51:03 EDT 2016


Hello,

I had an idea that has in some form been proposed before.  I think a random
weighted choice function would be a very good addition to the random module
in the python standard library.

Here's a basic implementation of what's required albeit slightly
inefficient as the search is linear as opposed to creating a binary tree
and taking log n time to find the correct choice. pmf is short for
probability mass function. It doesn't handle all error cases but it is more
of an example to show the idea.


    def randweighted(self,pmf=list):
        """Return an int in the range [0,len(list)] weighted by list of
values.
        Raises error if list is empty.
        """
        if(pmf == []):
            raise ValueError("pmf is equal to empty list")
        cummassf = [x[:i] for i in pmf]
        randVal = self._randbelow(len(pmf))
        for x in cummassf:
            if randVal < x:
                return x


There was a ticket that got started before.  It has since stalled because I
believe the original author intended the library to get called over an over
so they came up with generators which would be more efficient if passing in
the same list.  Otherwise there isn't really a point to using generators in
my opinion.

http://bugs.python.org/issue18844

~Steven
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160323/d5b4b310/attachment.html>


More information about the Python-ideas mailing list