鲁棒加权随机串发生器

时间:2014-01-15 20:32:33

标签: python

我已经实现了以下类,根​​据输入频率'p'生成'p'或'q'。但是,如果频率小于用于存储选项的列表的大小,则此实现会中断。有没有办法可以实现这个来处理p的任何值?

from random import random

class AlleleGenerator(object):
    """
    allele generator - will break if p < 0.001
    """
    def __init__(self, p):
        """construct class and creates list to select from"""
        self.values = list()
        for i in xrange(int(1000*p)):
            self.values.append('p')
        while len(self.values) <= 1000:
            self.values.append('q')
    def next(self):
        """Returns p or q based on allele frequency"""
        rnd = int(random() * 1000)
        return self.values[rnd]
    def __call__(self):
        return self.next()

1 个答案:

答案 0 :(得分:6)

请勿使用self.values。在next中,只需生成0到1之间的随机数,如果随机数小于'p',则返回p

from random import random

class AlleleGenerator(object):
    def __init__(self, p):
        """construct class and creates list to select from"""
        self.p = p
    def next(self):
        """Returns p or q based on allele frequency"""            
        return 'p' if random() < self.p else 'q'
    def __call__(self):
        return self.next()

另外,当功能足够时要小心not to use classes。 例如,您可以考虑使用generator function

from random import random

def allele_generator(p):
    while True:
        yield 'p' if random() < p else 'q'

agen = allele_generator(0.001)
for i in range(3):
    print(next(agen))