【问题标题】:Random sampling with Hypothesis带有假设的随机抽样
【发布时间】:2016-09-23 23:24:35
【问题描述】:

在假设中,有一个corresponding sampled_from() strategyrandom.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()-like 策略从序列中产生长度为 N 的子序列?

In [3]: import random

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

【问题讨论】:

    标签: python unit-testing testing random python-hypothesis


    【解决方案1】:

    你可以这样做:

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

    【讨论】:

      【解决方案2】:

      感觉lists 策略应该可以做到这一点,但我无法让它发挥作用。通过 aping 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]
      

      【讨论】:

      • 请不要这样做。 a) 继承自 SearchStrategy 是一个内部 API。继承结构不稳定。 b)在策略中使用随机方法会起作用,但不会正确最小化。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多