Skip to content

Instantly share code, notes, and snippets.

@igrep
Created January 31, 2011 14:00
Show Gist options
  • Save igrep/804053 to your computer and use it in GitHub Desktop.
Save igrep/804053 to your computer and use it in GitHub Desktop.
Choose an elements from sequence with weight at random.
#!/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