This follows on from this question:
Algorithm to generate spanning set
Given this input: [1,2,3,4]
I’d like to generate this set of sets in python:
[1] [2] [3] [4]
[1] [2] [3,4]
[1] [2, 3, 4]
[1] [2,3] [4]
[1,2] [3] [4]
[1,2] [3,4]
[1,2,3] [4]
[1,2,3,4]
So unlike the previous question, the order of the list is retained.
Ideally the code would work for n items in the list
Thanks very much
EDIT 2: Could anyone advise me on how to do this if the original input is a string rather than a list (where each word in the string becomes an item in a list). Thanks!
EDIT: added [1] [2, 3, 4] Sorry for the mistake
You might also enjoy a recursive solution:
Explanation
We exploit recursion here to break the problem down. The approach is the following:
For every list, the whole list is a valid spanning:
[1,2,3,4] => [[1,2,3,4]].For every list that is longer than size
1, we can use the first item as a group and then apply the same algorithm on the remaining list to get all the combined results:For every list that is longer than size
2, we can just as well use the first two items as a group and then apply the same algorithm on the remaining list and combine the results:We can see that the possible combinations on the right side are indeed all possible groupings of the remainder of the list,
[3,4,5].For every list that is longer than … etc. Thus, the final algorithm is the following:
yieldis a special keyword in Python that make the function a generator, which means that it returns a iterable object that can be used to enumerate all results found. You can transform the result into a list using thelistconstructor function:list(span([1,2,3,4])).