Over a million developers have joined DZone.

Weighted Random Choice

DZone's Guide to

Weighted Random Choice

· ·
Free Resource
From Kevin Parks's recipe

import random

def w_choice(lst):
	n = random.uniform(0, 1)
	for item, weight in lst:
		if n < weight:
		n = n - weight
	return item

Usage, similar to random.choice but must specify probabilities.

>>> x = w_choice( [('one',0.25), ('two',0.25), ('three',0.5)] )


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}