I am working on combination using python. Let's say I have the following list:
List = ['AW','BW','CW','DW','EW','FW','GW','HW']
I am creating combinations for any 3 as follow:
Perm =combinations( List,3)
Com = []
for i in list(Perm):
#print (i)
Com.append(i)
I got the following output with 56 combinations:
I want to remove the combinations with the following conditions:
Both
List [0]
andList [1]
contains in a combination (i.e. I want the combinations with only one of these two to contain in a combination.)Both
List [2]
andList [3]
contains in a combination (i.e. I want the combinations with only one of these two to contain in a combination.)Both
List [4]
andList [5]
contains in a combination (i.e. I want the combinations with only one of these two to contain in a combination.)
It means only one of two subsequent component () of list to be contained in a combination.
I have attached the picture and highlighted the combinations to be removed as examples.
Can anyone advise me on how to do this? Thanks and I appreciate your help.
Thinking as I write... You have a set of constraints where you only want one of (0,1), (2,3), (3,4)... We'll assume the list is even in length then and that you actually wanted to not include the very first item which violates the (0,1) constraint. Something like this should do the trick:
import itertools
test_list = ['AW', 'BW', 'CW', 'DW', 'EW', 'FW', 'GW', 'HW']
# Your combinations can be obtained with itertools.combinations(test_list, 3)
def get_constraints(a, b, *rest):
return [(a, b), *(get_constraints(*rest) if rest else [])]
def constrained(combination_list, constraints):
for constraint in constraints:
if all((constraint_name in combination_list) for constraint_name in constraint):
return True
return False
def constrained_combinations(name_list):
combinations = itertools.combinations(name_list, 3)
constraints = get_constraints(*name_list)
return [combination for combination in combinations if not constrained(combination, constraints)]
constrained_combinations(test_list) ->
[('AW', 'CW', 'EW'),
('AW', 'CW', 'FW'),
('AW', 'CW', 'GW'),
('AW', 'CW', 'HW'),
('AW', 'DW', 'EW'),
('AW', 'DW', 'FW'),
('AW', 'DW', 'GW'),
('AW', 'DW', 'HW'),
('AW', 'EW', 'GW'),
('AW', 'EW', 'HW'),
('AW', 'FW', 'GW'),
('AW', 'FW', 'HW'),
('BW', 'CW', 'EW'),
('BW', 'CW', 'FW'),
('BW', 'CW', 'GW'),
('BW', 'CW', 'HW'),
('BW', 'DW', 'EW'),
('BW', 'DW', 'FW'),
('BW', 'DW', 'GW'),
('BW', 'DW', 'HW'),
('BW', 'EW', 'GW'),
('BW', 'EW', 'HW'),
('BW', 'FW', 'GW'),
('BW', 'FW', 'HW'),
('CW', 'EW', 'GW'),
('CW', 'EW', 'HW'),
('CW', 'FW', 'GW'),
('CW', 'FW', 'HW'),
('DW', 'EW', 'GW'),
('DW', 'EW', 'HW'),
('DW', 'FW', 'GW'),
('DW', 'FW', 'HW')]