Last active
August 29, 2015 13:57
-
-
Save yuitest/9858301 to your computer and use it in GitHub Desktop.
重み付け乱択
This file contains hidden or 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
# coding: utf-8 | |
import random | |
import bisect | |
# 手本: http://qiita.com/methane/items/045982489cd7cf3720b3 | |
# 変更点: append のメソッドを追加。 | |
class WeightChoice(object): | |
def append(self, item, score): | |
self.total += score | |
self.range.append(self.total) | |
self.items.append(item) | |
def __init__(self, L=()): | |
self.total = 0 | |
self.range = [] | |
self.items = [] | |
for item, score in L: | |
self.append(item, score) | |
def choice(self): | |
if not self.items: | |
return None | |
r = random.random() * self.total | |
idx = bisect.bisect(self.range, r) | |
return self.items[idx] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment