4

In Hypothesis, there is an corresponding sampled_from() strategy to random.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'

But, is there a way to have random.sample()-like strategy to produce subsequences of length N out of a sequence?

In [3]: import random

In [4]: random.sample(('ST', 'LT', 'TG', 'CT'), 2)
Out[4]: ['CT', 'TG']
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195

2 Answers2

2

You could do:

permutations(elements).map(lambda x: x[:n])
DRMacIver
  • 2,259
  • 1
  • 17
  • 17
1

It feels like this should be possible with the lists strategy, but I couldn't make it work. By aping the sampled_from code, I was able to make something that seems to work.

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)

Sample result:

>>> find(sample_multiple_from([1, 2, 3, 4], 2), lambda x: True)
[4, 2]
bbayles
  • 4,389
  • 1
  • 26
  • 34
  • 2
    Please don't do it this way. a) Inheriting from SearchStrategy is an internal API. The inheritance structure isn't stable. b) Using random methods inside a strategy will work ish but won't minimize properly. – DRMacIver Sep 25 '16 at 13:59