#NEWLINE# def weighted_choice( mapping ) : #NEWLINE# #INDENT# 'Return a single element from a weighted sample.\n\n    The input is a dictionary of items with weights as values.\n    ' #NEWLINE# rnd = ( random . random ( ) * sum ( mapping . values ( ) ) ) #NEWLINE# for ( k , w ) in mapping . items ( ) : #NEWLINE# #INDENT# rnd -= w #NEWLINE# if ( rnd < 0 ) : #NEWLINE# #INDENT# return k