def w_choice(lst):This function will return the indeces from a sequence depending on the weights present in that sequence. We modified this code here to get the function above.

n = random.uniform(0, 1)

for item, weight in enumerate(lst):

if n < weight:

break

n = n - weight

return item

# testing

prob = [0.1, 0.2, 0.5, 0.2]

print w_choice(prob)

The code above assumes normalized weight vector, that is, all probability values in the vector should add to one. If the parameter passed into w_choice is not normalized, then this normalization can be performed with a single line of Python code at the beginning of w_choice:

lst = lst / sum(lst)

## No comments:

## Post a Comment