Search code examples
pythonpython-itertools

Conditions on itertools combinations Python


I would like to pre definited a condition on itertools combinations.

My problem: I need only combinations with 100 or less days difference.

Actually my code breaks the loop. I would like to cut and continue with the next combinations. Is it possible?

from itertools import combinations
for row in combinations(df.values, 5):
    E1_date, E2_date, E3_date, E4_date, E5_date = row[0][0], row[1][0], row[2][0], row[3][0], row[4][0]
    if E5_date - E1_date > 100:
        break
        # The combinations must not have more than 100 days of difference

Solution

  • Rather than filtering in your loop, pass the combination iterator to filter(). It's a little hard to use your data since you didn't provide an example of what you have, but here's a minimal example that hopefully will give you enough of an idea.

    With filter() you just give it a lambda function that returns True for the combinations you want and False for those you don't:

    from itertools import combinations
    
    values = list(range(10))
    
    # all 5 element combinations of 0-9 such that the difference
    # between the first and last is less than 6 
    combos = filter(lambda e: e[4] - e[0] < 6, combinations(values, 5))
    
    for row in combos:
        print(row, row[4] - row[0])
    

    Prints:

    (0, 1, 2, 3, 4) 4
    (0, 1, 2, 3, 5) 5
    (0, 1, 2, 4, 5) 5
    (0, 1, 3, 4, 5) 5
    (0, 2, 3, 4, 5) 5
    (1, 2, 3, 4, 5) 4
    (1, 2, 3, 4, 6) 5
    (1, 2, 3, 5, 6) 5
    ...
    (4, 5, 7, 8, 9) 5
    (4, 6, 7, 8, 9) 5
    (5, 6, 7, 8, 9) 4