choosing random numbers with weights/probability?

Darrell news at dorb.com
Mon Jun 21 21:57:58 CEST 1999


import time, whrandom

list1 = [('one', 0.25), ('two', 0.25), ('three', 0.5)]
def wc(list):
   from whrandom import uniform
   n = uniform(0, 1)
   for item, weight in list:
     if n < weight:
       break
     n = n - weight
   return item


def wc_test1(list, cnt=100000):
 t1=time.time()
 hist={}
 for i in range(cnt):
  k=wc(list)
  if hist.has_key(k):
          hist[k]=hist[k]+1
  else:
          hist[k]=1
        print " Time: %.2f sec"%(time.time()-t1)
 return hist

def popList(l):
 selList=[]
 for i in l:
   for v in range(i[1]):
   selList.append(i[0])
  return selList

list2=popList([('one',25),('two',50),('three',25)])

def wc_test2(list, cnt=100000):
 t1=time.time()
 hist={}
 list=popList([('one',25),('two',50),('three',25)])
 for i in range(cnt):
  k=whrandom.choice(list)
  if hist.has_key(k):
          hist[k]=hist[k]+1
  else:
          hist[k]=1
        print " Time: %.2f sec"%(time.time()-t1)
 return hist


wc_test1(list1)
 Time: 10.36 sec
{'one': 25069, 'three': 50087, 'two': 24844}
wc_test2(list2)
 Time: 4.52 sec
{'one': 24964, 'two': 50278, 'three': 24758}

Selecting from a list is faster.
--
--Darrell






More information about the Python-list mailing list