0

Possible Duplicate:
Weighted random selection with and without replacement

I have a long object list of items. I want to randomly select an item from the list based on the probability. The list looks like the following:

class Item:
  def __init__(self, pid, hits, qtyPerOrder):
    self.pid = pid
    self.bay = hits
    self.qtyPerOrder = int(qtyPerOrder)

itemList = [('RGSCAF', 181  ,6), ('WAR10227', 54    ,3), ('AD2020WOC', 31   ,4)]

Basically, I want a function that will go through the list, assign probability weights based on hits, then randomly choose n number of objects based on the probability. So in this example, there would be a higher probability that the object ('RGSCAF', 181 ,6) is returned since it has the highest hits value.

Community
  • 1
  • 1
user1683885
  • 81
  • 2
  • 5

1 Answers1

0

Not the fastest solution but it gets the point across:

def getNWeightedRandoms(n):
    retval = []
    for x in xrange(0,n):
        retval.append(weightedRandom())
    return retval

def weightedRandom():
    sum = 0
    for item in itemList:
        sum += item.bay
    i = random.randint(0,sum-1)
    for item in itemList:
        i -= item.bay
        if i<0:
            return item
DigitalGhost
  • 773
  • 1
  • 5
  • 14