from __future__ import absolute_import import random def smart_choice

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
from __future__ import absolute_import
import random
def smart_choice(items):
"""
Select random item from items counting their weights.
items is mapping a --> b:
* a: real item value
* b: item weight
"""
total_weight = sum(items.itervalues())
rnd = random.randint(1, total_weight)
weight = 0
for key, value in items.iteritems():
weight += value
if weight >= rnd:
return key