2016-09-23 3 views
1

Dans l'hypothèse, il y a une corresponding sampled_from() strategy-random.choice():échantillonnage aléatoire avec hypothèse

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' 

Mais, est-il un moyen d'avoir random.sample() -comme stratégie pour produire des séquences de longueur N sur une séquence?

In [3]: import random 

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

Répondre

1

Vous pourriez faire:

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

Beaucoup plus simple, merci beaucoup encore! – alecxe

1

Il se sent comme cela devrait être possible avec la stratégie lists, mais je ne pouvais pas le faire fonctionner. En utilisant le code sampled_from, j'ai réussi à faire quelque chose qui semble fonctionner.

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) 

Exemple de résultat:

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

S'il vous plaît ne pas le faire de cette façon. a) Hériter de SearchStrategy est une API interne. La structure d'héritage n'est pas stable. b) L'utilisation de méthodes aléatoires à l'intérieur d'une stratégie fonctionnera mais ne minimisera pas correctement. – DRMacIver