Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I add constraints to Itertools Product?

I am trying to list all products with numbers = [1,2,3,4,5,6,7,8] string length of 4 with some constraints.

  • Position 0 must be < 8
  • Positions 2 and 3 must be < 6

With the current code it is printing every possible combination so I was wondering how do I go about filtering it?

import itertools

number = [1,2,3,4,5,6,7,8]

result = itertools.product(number, repeat=4)

for item in result:
    print(item) 

I’ve tried using if product[0] < 8 or product[2] < 6 or product[3] < 6: but I don’t know where to fit in or how to format it.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I think you can simplify this and avoid wasting a lot of cycles by looking at the inputs carefully.

repeat=4 means that you want to iterate over the following:

[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8]

However, what your question is asking is how to iterate through

[1, 2, 3, 4, 5, 6, 7]
[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]

Since the conditions on the inputs are independent (the value of one element is not what restricts the others), you can adjust the inputs instead of filtering elements after the fact.

I suggest you just iterate over the sequences you want directly instead of filtering the output. You don’t need to make actual lists: a range object will be much more efficient:

itertools.product(range(1, 8), range(1, 9), range(1, 6), range(1, 6))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading