Reputation: 1243
I'm writing a code that should go over reg_lines and create all the permutations for (1) which lines to use with each protocol and (2) what lines to disconnect in order to check some functionality.
reg_lines = {'primary': ['ETH', 'UDP', 'TCP'], 'secondary': ['ETH', 'TCP'], 'private': ['UDP', 'TCP']}
Expected permutations:
1.
use = [{'primary':'ETH'}]
disc = [{'primary':'ETH'}]
use = [{'primary': 'TCP'}]
disc = [{'primary': 'TCP'}]
...
j.
use = [{'secondary': 'TCP'}]
disc = [{'secondary': 'TCP'}]
...
i.
use = [{'primary': 'ETH', 'secondary': 'ETH'}
disc = [{'primary': 'ETH'}]
i+1.
use = [{'primary': 'ETH', 'secondary': 'ETH'}]
disc = [{'primary': 'ETH'}]
i+2.
use = [{'primary': 'ETH', 'secondary': 'ETH'}]
disc = [{'primary': 'ETH', 'secondary': 'ETH'}]
...
n.
use = [{'primary': 'TCP', 'secondary': 'TCP', 'private': 'TCP'}]
disc = [{'primary': 'TCP', 'secondary': 'TCP', 'private': 'TCP'}]
Upvotes: 1
Views: 244
Reputation: 82949
First, use itertools.combinations
to get all the combinations of primary, secondary, and private, and then itertools.product
to get the product of those. Then use itertools.combinations
again to get all the subsets of those for the disc
dictionaries.
from itertools import product, combinations, chain
reg_lines = {'primary': ['ETH', 'UDP', 'TCP'], 'secondary': ['ETH', 'TCP'], 'private': ['UDP', 'TCP']}
def all_combinations(lst):
return chain(*[combinations(lst, i+1) for i in range(len(lst))])
for comb in all_combinations(reg_lines):
for prod in product(*(reg_lines[k] for k in comb)):
use = dict(zip(comb, prod))
print("use", use)
for comb2 in all_combinations(comb):
disc = {k: use[k] for k in comb2}
print("disc", disc)
Output:
use {'primary': 'ETH'}
disc {'primary': 'ETH'}
use {'primary': 'UDP'}
disc {'primary': 'UDP'}
... many many more ...
use {'primary': 'TCP', 'secondary': 'TCP', 'private': 'TCP'}
disc {'primary': 'TCP'}
disc {'secondary': 'TCP'}
disc {'private': 'TCP'}
disc {'primary': 'TCP', 'secondary': 'TCP'}
disc {'primary': 'TCP', 'private': 'TCP'}
disc {'secondary': 'TCP', 'private': 'TCP'}
disc {'primary': 'TCP', 'secondary': 'TCP', 'private': 'TCP'}
Upvotes: 1