0

I am not sure of the technical terminology for what I am trying to do, but this is the gist of it. I have the following list:

x = ['a', 'b', 'c']

I want to create a new list y where len(y) = 2 ** len(x) such that:

y = ['∅', 'a', 'b', 'c', 'a,b', 'a,c', 'b,c', 'a,b,c']

I am unsure of what operations to use when looping through x to create the desired list y.

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126

1 Answers1

1

Although this is much less efficient than itertools, if you are not allowed to use libraries, you could make a recursive function to produce the power-set and assemble the strings using join() in a list comprehension:

def powerSet(L):
    return [[]] if not L else [c for p in powerSet(L[1:]) for c in (p,L[:1]+p)]

x = ['a','b','c']
y = [",".join(s) or "ø" for s in powerSet(x)]

print(y)
['ø', 'a', 'b', 'a,b', 'c', 'a,c', 'b,c', 'a,b,c']

You can also do this directly in an iterative function that extends all previous combinations with each letter in the list:

def allCombos(L):
    result = [""]
    for c in L:
        result.extend([f"{r},{c}" if r else c for r in result])
    result[0] = "ø"
    return result

print(allCombos(x))
['ø', 'a', 'b', 'a,b', 'c', 'a,c', 'b,c', 'a,b,c']
Alain T.
  • 40,517
  • 4
  • 31
  • 51