1

I am not positive if this is a combination or a permutation question.

I have a list of 4 topics

topics = ['A', 'B', 'C', 'D']

Each of these topics can have a state of on or off

state = [1, 0]

How would I go about listing out all possible combinations?

I am thinking a result something like this (df as example doesn't have to be a df):

     A B C D
0    1 1 1 1
1    0 0 0 0
2    1 0 0 0
3    1 0 0 1
1
  • @Charley I was just using the 0’s and 1’s to help me get an idea of how I was going to make several groupby and wasn’t sure how many different ones I would need. It looks like @ SciencSnake solution is what I was looking for. Now I know that I need 16 combinations and what to turn “on” and “off” for each one.
    – alws_cnfsd
    Commented Feb 6, 2021 at 2:53

2 Answers 2

2
import itertools
list(itertools.product([0, 1], repeat=len(topics)))

Which will also give them in increasing order as binary numbers

0
-1

Using the powerset recipe from itertools recipes

In a powerset, there are 2**len(list) outcomes (here with 4 items in the list, there are 2**4 == 16 outcomes).

from itertools import combinations, chain

def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))

for pset in powerset(['A','B','C','D']):
    print(pset)

Prints:

()
('A',)
('B',)
('C',)
('D',)
('A', 'B')
('A', 'C')
('A', 'D')
('B', 'C')
('B', 'D')
('C', 'D')
('A', 'B', 'C')
('A', 'B', 'D')
('A', 'C', 'D')
('B', 'C', 'D')
('A', 'B', 'C', 'D')

Not the answer you're looking for? Browse other questions tagged or ask your own question.