[英]How can I generate a hypothesis strategy to generate a list that contains at least one of each element it samples from?
I am looking for a way to build a Hypothesis strategy such that each element in a given list is present in the generated list.我正在寻找一种方法来构建假设策略,以便给定列表中的每个元素都存在于生成的列表中。
eg例如
Assuming that we have假设我们有
values = [0, 1, 2, 3, 5, 8]
we want a strategy that generates lists from given values such that each element appears at least once, eg我们想要一种策略,从给定值生成列表,使得每个元素至少出现一次,例如
[0, 1, 2, 3, 5, 8]
[2, 1, 0, 3, 5, 8]
[0, 0, 1, 2, 3, 5, 8]
[0, 0, 0, 1, 2, 3, 5, 8]
[5, 2, 5, 2, 8, 2, 0, 8, 3, 2, 0, 5, 5, 3, 5, 5, 5, 1]
I am getting errors in my program because I need to select a value that does not exist in a list that uses the sampled_from
strategy.我的程序出现错误,因为我需要 select 一个在使用
sampled_from
策略的列表中不存在的值。 (presumably with a large enough list, the probability that such a value would appear grows, however I am working with expensive objects, and that seems like a workaround) (大概有足够大的列表,出现这样一个值的可能性会增加,但是我正在使用昂贵的对象,这似乎是一种解决方法)
I have spent quite some time trying to figure out if any of the strategies enforce that certain values will appear in the generated values -- fixed_dictionaries
seems to be the only one -- and I am struggling to even come up with a simple composite strategy.我花了很长时间试图弄清楚是否有任何策略强制某些值将出现在生成的值中
fixed_dictionaries
似乎是唯一的——我什至在努力想出一个简单的复合策略。
We can use strategies.lists
and then concatenate with values
so that every value is presented and then shuffle我们可以使用
strategies.lists
然后与values
连接,以便呈现每个值,然后随机播放
from hypothesis import strategies
sub_values = (strategies.lists(strategies.sampled_from(values))
.map(lambda sublist: sublist + values)
.flatmap(strategies.permutations))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.