I have a bunch of keys that each have an unlikeliness variable. I want to randomly choose one of these keys, yet I want it to be more unlikely for unlikely (key, values) to
You want to give each object a weight. The bigger the weight the more likely it will happen. More precisely probx =weight/sum_all_weights.
Then generate a random number in the range 0 to sum_all_weights and map it to each object.
This code allows you to generate a random index and it is mapped when the object is created for speed. If all of your sets of objects have the same distribution then you can get by with only one RandomIndex object.
import random
class RandomIndex:
def __init__(self, wlist):
self._wi=[]
self._rsize=sum(wlist)-1
self._m={}
i=0
s=wlist[i]
for n in range(self._rsize+1):
if n == s:
i+=1
s+=wlist[i]
self._m[n]=i
def i(self):
rn=random.randint(0,self._rsize)
return self._m[rn]
sx=[1,2,3,4]
wx=[1,10,100,1000] #weight list
ri=RandomIndex(wx)
cnt=[0,0,0,0]
for i in range(1000):
cnt[ri.i()] +=1 #keep track of number of times each index was generated
print(cnt)