sandbox /

from __future__ import print_function

import random
import operator
from collections import namedtuple

from jaraco.util.dictlib import RangeMap

Entrant = namedtuple('Entrant', 'id volume')
entrants = [
	Entrant(1, 1),
	Entrant(2, 5),
	Entrant(3, 3),
	Entrant(4, 1),
	# ...

def calculate_accumulated_volumes(entrants):
	# make acc_volume there so we have total
	global acc_volume
	acc_volume = 0
	for entrant in entrants:
		acc_volume += entrant.volume
		yield acc_volume

# create a map where a volume between 0 and total_volume produces gives
#  a weighted selection of Entrants.

weighted_entrants = RangeMap(zip(calculate_accumulated_volumes(entrants), entrants),

# test our bounds
assert weighted_entrants[0] == Entrant(1,1)
assert weighted_entrants[0.99999] == Entrant(1,1)
assert weighted_entrants[1] == Entrant(2,5)
assert weighted_entrants[6] == Entrant(3,3)
except KeyError:
	raise ValueError("Expected exception")

# now pick an entrant
for x in range(3):
	index = random.uniform(0, acc_volume)
	pick = weighted_entrants[index]
	print('picked', pick, '(%s)' % index)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.