0

Possible Duplicates:
Random weighted choice
Select random k elements from a list whose elements have weights

Let's say I have a set of N objects,

set = range(a,b) = [a,a+1,...b-2, b-1]

To select M number of objects with probability 1/len(N), I can do:

random.sample(set, M).

I want to able to select objects at random with a weighted probability. For example, if not a multiple of 3 or 5, weighted probability will be 1. If a multiples of 3, weighted probability will be 3, if a multiple of 5, weighted probability will be 5, if a multiple of 15, weighted probability will be 15.

To illustrate:

set = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
weighted_set=[(1, weight=1), (2, weight=1), (3, weight=3),(4, weight=1), (5, weight=5),...(15, weight=15)]
random.sample(weighted_set, N)

How would I do something like this? Thank you.

Community
  • 1
  • 1
David542
  • 104,438
  • 178
  • 489
  • 842
  • I took a look at that question, and am going to modify this one to make it different in that there are an unknown amount of objects to start with. – David542 Jun 21 '11 at 19:10
  • When I was implementing something similar I found this post interesting and useful: http://stackoverflow.com/questions/352670/weighted-random-selection-with-and-without-replacement – carlpett Jun 21 '11 at 19:26
  • This appears to be the answer: http://stackoverflow.com/questions/2140787/select-random-k-elements-from-a-list-whose-elements-have-weights/2149533#2149533 – David542 Jun 21 '11 at 19:55

1 Answers1

4

You can use code like this to weigh items, by just adding them multiple times to a different set.

set = [1,2,3,4,5,6,7,8,9,10]
weight = 5
weighted_set = []
for i in set:  
    if i % 5 == 0:
        weighted_set += weight*[i]
    else:
        weighted_set += [i]
gnur
  • 4,671
  • 2
  • 20
  • 33
  • thanks for the response. And then once I have the weighted set, what would be the syntax/method to select an object from it (e.g., random.sample) ? – David542 Jun 21 '11 at 19:19