I am trying to list all products with numbers = [1,2,3,4,5,6,7,8] string length of 4 with some constraints.
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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With