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']
4

2 回答 2

2

你可以这样做:

permutations(elements).map(lambda x: x[:n])
于 2016-09-25T13:59:18.267 回答
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]
于 2016-09-24T02:55:09.550 回答