You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

创建非均匀选择策略C的技术咨询:Hypothesis中cu.integer_range的使用

实现加权策略C:90%选A,10%选B

Absolutely! You can use Hypothesis's hypothesis.internal.conjecture.utils.integer_range to build your weighted strategy, but first let's cover both the official (and more maintainable) approach, plus how to implement it with the internal utility if you specifically need that.

官方推荐方式:使用st.one_of的权重参数

Hypothesis's built-in st.one_of supports weighted selection directly—you don't need to mess with internal utilities for this use case. Here's how to define your strategy C cleanly:

import hypothesis.strategies as st

# 先定义你的基础策略A和B(替换成你实际的策略逻辑)
strategy_a = st.integers(min_value=1, max_value=10)
strategy_b = st.integers(min_value=100, max_value=200)

# 用权重参数创建策略C:90%概率选A,10%选B
strategy_c = st.one_of(
    (0.9, strategy_a),
    (0.1, strategy_b)
)

This approach is fully supported by Hypothesis, won't break across version updates, and handles all the random state management correctly—you won't run into the "same random value every time" issue you saw with the standard random library, because Hypothesis manages its own random state tied to test case generation.

使用cu.integer_range实现自定义加权策略

If you specifically want to use hypothesis.internal.conjecture.utils.integer_range (e.g., for more complex custom logic), you can do that with a composite strategy. Here's how:

First, import the necessary modules:

import hypothesis.strategies as st
import hypothesis.internal.conjecture.utils as cu

Then define your composite strategy:

@st.composite
def strategy_c(draw):
    # 生成0-9的整数:0-8(9个值)对应策略A(90%概率),9对应策略B(10%概率)
    random_idx = draw(cu.integer_range(draw.data, 0, 9))
    
    if random_idx < 9:
        return draw(strategy_a)
    else:
        return draw(strategy_b)

为什么这比直接用random库有效

cu.integer_range使用Hypothesis的ConjectureData对象(通过draw.data传递)生成随机值。和全局状态的random库不同,Hypothesis的ConjectureData会追踪测试用例生成的状态——即使你设置了固定种子,每个新测试用例都会使用不同的随机路径,所以不会出现每次生成都得到相同值的问题。

关于内部工具的重要提醒

要注意hypothesis.internal下的模块不属于Hypothesis的公开API,它们可能在未来版本中毫无预警地修改或移除。对于生产环境或长期维护的代码,官方的st.one_of加权方案永远是更稳妥的选择。

内容的提问来源于stack exchange,提问作者curious_george

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:41:12