How to implement roulette wheel for picking random objects in python?
Question: In python, I have a list of objects (size of list is >= 2), which have a
property called `score` which has a value which is any float that's >= 0 (no
upper bound).

I want to randomly pick 2 different objects from the list, but make sure that
there is a higher chance of picking a value that has a higher score. Basically
the higher the score the more chance of being picked. I was thinking of doing
a roulette style, where I take a sum of all scores, and then getting a perfect
of each item where it's percent is its score divided by the total score.

But how do I still pick the 2 objects?

Thanks


Answer: The question is not super clear, but I think I get what you mean. You should
use a inverse CDF type approach. The below example will return you an index
for your list of scores, then just use that to get the value you want.
Obviously there are smarter ways to do this from a programming point of view,
but you clearly need to understand the method, which I think this example will
help a lot with.

    
    
    >>> import numpy as np
    >>> import pandas as pd
    >>> scores = [100, 200, 300, 400, 500]
    >>> scores = np.array(scores)
    >>> sum = scores.sum()
    >>> sum
    1500
    >>> percentages = scores/float(sum)
    >>> percentages
    array([ 0.06666667,  0.13333333,  0.2       ,  0.26666667,  0.33333333])
    >>> cdf = percentages.cumsum()
    >>> cdf
    array([ 0.06666667,  0.2       ,  0.4       ,  0.66666667,  1.        ])
    >>> cdf = np.concatenate([np.array([0]), cdf])
    >>> cdf
    array([ 0.        ,  0.06666667,  0.2       ,  0.4       ,  0.66666667,  1.        ])
    >>>def returnobj(cdf, randnum):
    >>>    for i in range(len(cdf)-1):
    >>>        if((randnum>cdf[i])&(randnum<=cdf[i+1])):
    >>>            return i
    ##########
    #This Bit is just to show how the results look, and to show it favours higher scores
    >>>for i in range(10000):
    >>>    results.append(returnobj(cdf, np.random.random()))
    >>>results=pd.DataFrame(results)
    >>>results[results.columns[0]] = results[results.columns[0]].astype(str)
    >>>results['a'] = results[0]
    >>>print results.groupby(0).count()
    0   639
    1  1375
    2  2039
    3  2678
    4  3269
    

