最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Forcing numpy arrays generated by Python hypothesis to contain all allowed elements - Stack Overflow

programmeradmin0浏览0评论

I generate test data using Python's hypothesis library.

For example, I am generating a numpy array that may contain 0 and 1 like this:

arr = hypothesis.extra.numpy.arrays(dtype=np.int8, shape=10, elements=st.integers(0, 1))

How can I make sure, that the generated arr always contains all allowed elements? That is, arr needs to contain at least one 0 and one 1.

I also need to ensure that I return an np.array of dtype=np.int8 with a specific shape.

I generate test data using Python's hypothesis library.

For example, I am generating a numpy array that may contain 0 and 1 like this:

arr = hypothesis.extra.numpy.arrays(dtype=np.int8, shape=10, elements=st.integers(0, 1))

How can I make sure, that the generated arr always contains all allowed elements? That is, arr needs to contain at least one 0 and one 1.

I also need to ensure that I return an np.array of dtype=np.int8 with a specific shape.

Share Improve this question edited Nov 20, 2024 at 10:15 Andi asked Nov 20, 2024 at 7:59 AndiAndi 4,8995 gold badges33 silver badges63 bronze badges 2
  • This question is similar to: How can I generate a hypothesis strategy to generate a list that contains at least one of each element it samples from?. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. – Kraigolas Commented Nov 20, 2024 at 8:08
  • This question points in the right direction, however, I need a numpy array where I can specify the dtype and the exact shape. – Andi Commented Nov 20, 2024 at 8:24
Add a comment  | 

1 Answer 1

Reset to default 0

In this case, I think that filtering is probably the best way forward: generate any array, and throw away the small fraction that don't meet your requirements.

arrays(
    dtype=np.int8, 
    shape=10,  # or `(2, 3)`, or whatever shape you desire
    elements=st.integers(0, 1)
).filter(
    lambda arr: {0, 1}.issubset(arr.flatten())
)
发布评论

评论列表(0)

  1. 暂无评论