Returns a value from choices chosen by weighted random selection choices should be a list of (value, weight) tuples. eg. weighted_choice([('val1', 5), ('val2', 0.3), ('val3', 1)])
(choices)
| 12 | |
| 13 | |
| 14 | def weighted_choice(choices): |
| 15 | """Returns a value from choices chosen by weighted random selection |
| 16 | |
| 17 | choices should be a list of (value, weight) tuples. |
| 18 | |
| 19 | eg. weighted_choice([('val1', 5), ('val2', 0.3), ('val3', 1)]) |
| 20 | |
| 21 | """ |
| 22 | values, weights = zip(*choices) |
| 23 | total = 0 |
| 24 | cum_weights = [] |
| 25 | for w in weights: |
| 26 | total += w |
| 27 | cum_weights.append(total) |
| 28 | x = random.uniform(0, total) |
| 29 | i = bisect.bisect(cum_weights, x) |
| 30 | return values[i] |
no outgoing calls
no test coverage detected
searching dependent graphs…