Created
January 31, 2011 14:00
-
-
Save igrep/804053 to your computer and use it in GitHub Desktop.
Choose an elements from sequence with weight at random.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import random | |
def choice_by(seq, criteria): | |
""" | |
Choose an elements from sequence with weight at random. | |
""" | |
#Initial value | |
itr = iter(seq) | |
chosen_so_far = itr.next() | |
cumsum = criteria( chosen_so_far ) | |
#Choose | |
for next_node in itr: | |
threshold = criteria( next_node ) | |
cumsum += threshold | |
r = random.random() * cumsum | |
if r < threshold: | |
chosen_so_far = next_node | |
#else: chosen_so_far is not changed | |
return chosen_so_far | |
if __name__ == '__main__': | |
k_weight = { 'A': 1, 'B': 1.5, 'C': 0 } | |
k_count = { 'A': 0, 'B': 0, 'C': 0 } | |
cri = lambda k: k_weight[k] | |
for i in range(50000): | |
k_count[ choice_by( k_weight, cri ) ] += 1 | |
print k_count # e.g. => {'A': 19922, 'C': 0, 'B': 30078} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment