[FRPythoneers] Weighted List

Bob Gailer bgailer at alum.rpi.edu
Tue May 6 13:55:37 MDT 2003

At 11:42 AM 5/6/2003 -0600, Dhruva B. Reddy wrote:

>I would like to choose elements from a list at random, but weight these

I assume you want some elements to be chosen more frequently than others. 
True? Here's my first cut at a solution. It is not working right, and I'm 
out of time to fix it right now. If you can tweak it, go ahead; I'' revisit 
it later. (Some of this could be simplified by using arrays as in numeric 

from random import randrange
elements = [2,5,9,13,22]
nElements = len(elements)
weights = [1,3,5,4,2]
# meaning: make 150 choices we'd get approximately 10 2s, 30 5s, 50 9s, 40 
13s and 20 22s randomly arranged.
buckets = [weights[0]]
nBuckets = len(buckets)
for weight in weights[1:]:
   buckets.append(buckets[-1] + weight)
results = []
for i in range(15):
   candidate = randrange(buckets[-1])
   for j in range(nBuckets):
     if candidate <= buckets[j]:
print results

Bob Gailer
bgailer at alum.rpi.edu
303 442 2625
-------------- next part --------------

Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.474 / Virus Database: 272 - Release Date: 4/18/2003

More information about the FRPythoneers mailing list