List of possible combinations of characters with OR statement

Viewed 79

I managed to generate a list of all possible combinations of characters 'a', 'b' and 'c' (code below). Now I want to add a fourth character, which can be either 'd' or 'f' but NOT both in the same combination. How could I achieve this ?

items = ['a', 'b', 'c']
from itertools import permutations
for p in permutations(items):
     print(p)

('a', 'b', 'c')
('a', 'c', 'b')
('b', 'a', 'c')
('b', 'c', 'a')
('c', 'a', 'b')
('c', 'b', 'a')
4 Answers

Created a new list items2 for d and f. Assuming that OP needs all combinations of [a,b,c,d] and [a,b,c,f]

items1 = ['a', 'b', 'c']
items2 = ['d','f']
from itertools import permutations
for x in items2:
    for p in permutations(items1+[x]):
        print(p)

A variation on @Van Peer's solution. You can modify the extended list in-place:

from itertools import permutations
items = list('abc_')
for items[3] in 'dg':
    for p in permutations(items):
        print(p)

itertools.product is suitable for representing these distinct groups in a way which generalizes well. Just let the exclusive elements belong to the same iterable passed to the Cartesian product.

For instance, to get a list with the items you're looking for,

from itertools import chain, permutations, product

list(chain.from_iterable(map(permutations, product(*items, 'df'))))

# [('a', 'b', 'c', 'd'),
#  ('a', 'b', 'd', 'c'),
#  ('a', 'c', 'b', 'd'),
#  ('a', 'c', 'd', 'b'),
#  ('a', 'd', 'b', 'c'),
#  ('a', 'd', 'c', 'b'),
#  ('b', 'a', 'c', 'd'),
#  ('b', 'a', 'd', 'c'),
#  ('b', 'c', 'a', 'd'),
#  ('b', 'c', 'd', 'a'),
#  ('b', 'd', 'a', 'c'),
#  ('b', 'd', 'c', 'a'),
#  ('c', 'a', 'b', 'd'),
#  ('c', 'a', 'd', 'b'),
#  ...

like this for example

items = ['a', 'b', 'c','d']
from itertools import permutations
for p in permutations(items):
     print(p)

items = ['a', 'b', 'c','f']
from itertools import permutations
for p in permutations(items):
     print(p)
Related