This question is probably a combination of following two questions, but with slightly different perspective.
Yield sub combinations with limit
I adapted the code in first question for my requirement.
def sub_combinations(segment):
for i in range(1, len(segment)):
for j in sub_combinations(segment[i:]):
yield [segment[:i]] + j
yield [segment]
max = 4
for p in sub_combinations([1, 2, 3, 4, 5, 6, 7]):
if len(p) == max:
print map(list, p)
This gives output as:
[[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]]
[[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]]
[[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]]
[[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]]
[[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]]
Now the problem is, this takes too much time for larger sized lists. Is there more efficient/pythonic way of implementing this? How could I incorporate argument 'max' in the function itself? I tried a lot of ways, but having hard time working with recursive functions.