假设随机抽样

2024-05-22 09:36:41 发布

您现在位置:Python中文网/ 问答频道 /正文

在假设中,有一个corresponding ^{} strategy^{}

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'

但是,有没有一种方法可以用^{}样的策略从序列中产生长度为N的子序列吗?在

^{pr2}$

Tags: infromimportltas序列tgfind
2条回答

你可以:

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

我觉得这应该可以用lists策略实现,但我无法使其发挥作用。通过仿效^{}代码,我能够做出一些似乎有效的东西。在

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)

样品结果:

^{pr2}$

相关问题 更多 >