Follows on from this question Algorithm to generate (not quite) spanning set in Python
Given n items in a list, for example n = 7, so this input: [1,2,3,4,5,6,7]
I’d like to generate this set of sets in python:
[1] [2] [3] [4] [5] [6] [7]
[1] [2] [3] [4] [5] [6, 7]
[1] [2] [3] [4] [5, 6, 7]
...
...
[1, 2, 3, 4, 5] [6, 7]
But not:
[1, 2, 3, 4, 5, 6] [7]
or
[1, 2, 3, 4, 5, 6, 7]
From the previous question I have this great answer:
def span(lst):
yield [lst]
for i in range(1, len(lst)):
for x in span(lst[i:]):
yield [lst[:i]] + x
Is it possible to work within this existing code to produce this more specific output
Thanks
While you could of course just filter the result of the original function using a comprehension like
(s for s in span(lst) if max(len(g) for g in s) <= 5), here I present you a recursive solution that doesn’t create the invalid results in the first place:The logic is very similar, although we can’t make use of the
yield [lst]“trick” to avoid having to explicitly state the terminating conditionlen(lst) == 0. I actually think this is cleaner, overall 🙂Note how this is a generalization of the original function: If you don’t give it a second argument, it will work the same way the old function did.