Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 209
CluelessDumbo Avatar asked Nov 26 '25 03:11

CluelessDumbo


1 Answers

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))
like image 149
Mad Physicist Avatar answered Nov 27 '25 17:11

Mad Physicist



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!