0

I'm writing a function that samples inputs to another numerical function that has 5 inputs, with given min and max values for each input. It should result in num_samples^5 different input combinations.

I would like to make this piece of code shorter such that the explicit indices 0 to 4 are not needed anymore.

num_inputs = 5
num_samples = 10.0

sampled_inputs = [[a, b, c, d, e]
                  for a in sample_range(mins[0], maxes[0], num_samples)
                  for b in sample_range(mins[1], maxes[1], num_samples)
                  for c in sample_range(mins[2], maxes[2], num_samples)
                  for d in sample_range(mins[3], maxes[3], num_samples)
                  for e in sample_range(mins[4], maxes[4], num_samples)]

where sample_range is a function that samples num_samples numbers between min and max.

Is there any trick I'm not seeing yet? Thanks in advance.

1 Answer 1

1

Are you trying to get a cartesian product here?

If so, use itertools.product.

import itertools
lists = [sample_range(mins[i], maxes[i], num_samples) for i in range(4)]
prod = itertools.product(*lists)
for elem in prod:
   print(elem)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, yes, after thinking about it, it is a cartesian product.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.