[Python-Dev] [Python-checkins] r86924 - python/branches/py3k/Doc/library/random.rst (original) (raw)
Nick Coghlan ncoghlan at gmail.com
Thu Dec 2 04:14:12 CET 2010
- Previous message: [Python-Dev] [Preview] Comments and change proposals on documentation
- Next message: [Python-Dev] [Python-checkins] r86924 - python/branches/py3k/Doc/library/random.rst
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
On Thu, Dec 2, 2010 at 12:41 PM, raymond.hettinger <python-checkins at python.org> wrote:
+A more general approach is to arrange the weights in a cumulative probability +distribution with :func:
itertools.accumulate
, and then locate the random value +with :func:bisect.bisect
:: + + >>> choices, weights = zip(*weightedchoices) + >>> cumdist = list(itertools.accumulate(weights)) + >>> x = random.random() * cumdist[-1] + >>> choices[bisect.bisect(cumdist, x)] + 'Blue'
Neat example, although it would be easier to follow if you broke that last line into two pieces:
.>>> random_index = bisect.bisect(cumdist, x) .>>> choices[random_index] 'Blue'
It took me a moment to remember how bisect.bisect worked, but it would have been instant if the return value was assigned to an appropriately named variable.
Cheers, Nick.
-- Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
- Previous message: [Python-Dev] [Preview] Comments and change proposals on documentation
- Next message: [Python-Dev] [Python-checkins] r86924 - python/branches/py3k/Doc/library/random.rst
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]