mardi 10 avril 2018

generating conditional data with Hypothesis Python

I want to generate a list of lists of integers of size 2 with the following conditions.

  • the first element should be smaller than the second and
  • all the data should be unique.

I could generate each tuple with a custom function but don't know how to use that to satisfy the second condition.

from hypothesis import strategies as st

@st.composite
def generate_data(draw):
    min_val, max_val = draw(st.lists(st.integers(1, 1e2), min_size=2, max_size=2))
    st.assume(min_val < max_val)
    return [min_val, max_val]

I could generate the data by iterating over generate_date a few times in this (inefficient ?) way:

>>> [generate_data().example() for _ in range(3)]
    [[5, 31], [1, 12], [33, 87]]

But how can I check that the data is unique?

E.g, the following values are invalid:

[[1, 2], [1, 5], ...]  # (1 is repeated)
[[1, 2], [1, 2], ...]  # (repeated data)

but the following is valid:

[[1, 2], [3, 4], ...]

Aucun commentaire:

Enregistrer un commentaire