Search code examples
pythonfor-loopiterationpython-itertools

How to skip some iterations when using itertools.product?


Suppose there are three sorted lists, A, B, C.

A = [1, 2, 3, 4]
B = [3, 4, 5]
C = [2, 3, 4]

I am using itertools.product to find all possible combination whose sum is smaller than 10.

If I have three lists only, I will use the following code.

A = [1, 2, 3, 4] B = [3, 4, 5] C = [2, 3, 4]

for a in A:
    for b in B:
        for c in C:
            if a + b + c < 10:
                print(a, b, c)
            else:
                break

Here, every list is sorted, and thus I used break for efficiency.

But when I using itertools.product, then how I use the break? I mean how go to directly specific iteration (e.g., a = 3, b = 3, c = 3)?

for a, b, c in itertools.product(A, B, C):
   ....?

Solution

  • You can try the following:

    from itertools import product, dropwhile
    
    A = [1, 2, 3, 4] 
    B = [3, 4, 5] 
    C = [2, 3, 4]
    
    for a, b, c in dropwhile(lambda x: x != (3,3,3), product(A, B, C)):
        print(a, b, c)
    

    It gives:

    3 3 3
    3 3 4
    3 4 2
    3 4 3
    3 4 4
    . . .
    

    Note that this does not really go directly to the given iteration. Instead, itertools.dropwhile runs the iterator until the specified condition is met, and only then starts returning its values.