假设随机抽样

Random sampling with Hypothesis

在假设中,有一个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'

但是,有没有一种方法可以使用类似 random.sample() 的策略从序列中生成长度为 N 的子序列?

In [3]: import random

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

感觉 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]

你可以这样做:

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