Given this input: [1,2,3,4]
I\'d like to generate the set of spanning sets:
[1] [2] [3] [4]
[1] [2] [3,4]
[1] [2,3] [4]
[1] [3] [2,4]
[1,2] [3] [4]
[1,3]
This should work, though I haven't tested it enough.
def spanningsets(items):
if not items: return
if len(items) == 1:
yield [[items[-1]]]
else:
for cc in spanningsets(items[:-1]):
yield cc + [[items[-1]]]
for i in range(len(cc)):
yield cc[:i] + [cc[i] + [items[-1]]] + cc[i+1:]
for sset in spanningsets([1, 2, 3, 4]):
print ' '.join(map(str, sset))
Output:
[1] [2] [3] [4]
[1, 4] [2] [3]
[1] [2, 4] [3]
[1] [2] [3, 4]
[1, 3] [2] [4]
[1, 3, 4] [2]
[1, 3] [2, 4]
[1] [2, 3] [4]
[1, 4] [2, 3]
[1] [2, 3, 4]
[1, 2] [3] [4]
[1, 2, 4] [3]
[1, 2] [3, 4]
[1, 2, 3] [4]
[1, 2, 3, 4]