Random from Dictionary

Max M maxm at mxm.dk
Sun Feb 22 21:20:46 CET 2004


Tobias Klausmann wrote:

> Still, it doesn't quite satisfy me. While I have a strong belief
> in its correctness, I'd be glad if others think so, too :)
> 
> Better yet, a faster and proven way to do this would be even
> nicer.


This class might work...


regards Max M

#################################

from random import random
from bisect import bisect


class Selector:

     "Returns random elements by probability according to their frequency"

     def __init__(self, frequencies, elements):
         self.sum = sum(frequencies)
         acumulated_frequencies = []
         acumulated_frequency = 0
         for frequency in frequencies:
             acumulated_frequency += frequency
             acumulated_frequencies.append(acumulated_frequency)
         self.decorated = zip(acumulated_frequencies, elements)
         self.decorated.sort()

     def get(self):
         "Randomly returns an element by probability"
         rnd = random() * self.sum
         index = bisect(self.decorated, (rnd, 0))
         return self.decorated[index][-1]

     def get_range(self, n):
         "Randomly returns a range of elements by probability"
         return [self.get() for itm in xrange(n)]






More information about the Python-list mailing list