在假设中,corresponding sampled_from()
strategy到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']
答案 0 :(得分:2)
你可以这样做:
permutations(elements).map(lambda x: x[:n])
答案 1 :(得分: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]