MCPcopy
hub / github.com/postmanlabs/httpbin / weighted_choice

Function weighted_choice

httpbin/utils.py:14–30  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

12
13
14def 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]

Callers 1

view_status_codeFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…