2016-09-23 44 views
1

在假设随机抽样,有一个corresponding sampled_from() strategyrandom.choice()与假说

In [1]: from hypothesis import find, strategies as st 

In [2]: find(st.sampled_from(('ST', 'LT', 'TG', 'CT')), lambda x: True) 
Out[2]: 'ST' 

但是,有一种方法来有random.sample()样的策略,以产生长度为N个子序列进行序列的?

In [3]: import random 

In [4]: random.sample(('ST', 'LT', 'TG', 'CT'), 2) 
Out[4]: ['CT', 'TG'] 

回答

1

你可以这样做:

permutations(elements).map(lambda x: x[:n]) 
+0

简单得多,再次感谢! – alecxe

1

感觉这应该可以用lists策略,但我不能让它工作。通过编写代码sampled_from,我能够做出似乎可行的事情。

from random import sample 
from hypothesis.searchstrategy.strategies import SearchStrategy 
from hypothesis.strategies import defines_strategy 


class SampleMultipleFromStrategy(SearchStrategy): 
    def __init__(self, elements, n): 
     super(SampleMultipleFromStrategy, self).__init__() 
     self.elements = tuple(elements) 
     if not self.elements: 
      raise ValueError 
     self.n = int(n) 

    def do_draw(self, data): 
     return sample(self.elements, self.n) 

@defines_strategy 
def sample_multiple_from(elements, n): 
    return SampleMultipleFromStrategy(elements, n) 

样品结果:

>>> find(sample_multiple_from([1, 2, 3, 4], 2), lambda x: True) 
[4, 2] 
+1

请不要做这种方式。 a)从SearchStrategy继承是一个内部API。继承结构不稳定。 b)在策略中使用随机方法将工作,但不会正确地最小化。 – DRMacIver