dimanche 12 août 2018

Python Random choice with 'percentage'

Foreword

It looks like it is a duplicate of few stackoverflow question but my situation is (probably) slightly unique.

My situation

I have a dictionary. The key is a string and the value is an integer.

I want the python script to randomly choose N number of keys.

The value is how likely it is to be chosen. The higher the key's value is, the higher the chance the key will be randomly chosen.

My solution

So using some other StackOverflow post and the power of the internet I managed to solve it using Weighted Random.

DICT_VAR= {'best':308281009, 'good':7066325, 'meh':26884, 'bad':71, 'terrible':16, 'never':0}

list_var = []
for i in DICT_VAR.keys():
    list_var.extend([i]*DICT_VAR[i])

print random.sample(list_var, 2) # get 2 random choice I suppose

The issue (the catch)

As you may notice, the value in the dictionary can be incredibly big (It can be unlimitedly big) and it can also be as small as 0 (zero is smallest, there is no negative number).

Running this code (with a little bigger numbers) resulted in my computer to freeze and be unresponsive until I hard reset it.

My question

How should I deal with the situation? Is there any other way of randomly choosing that is suitable for my situation since Weighted Random is the worst possible solution to this current case.




Aucun commentaire:

Enregistrer un commentaire