'How do I get all possible set partition of a list with maximum size limit of each subset?
Here is what I am trying to do. Given a number k and a set of numbers, I want to partition the set with elements of size not bigger than k.
Ex) lst = [1, 2, 3, 4], k=2
All possible set partition of lst is as follows. codes are in previous question below: (Set partitions in Python)
1 [[1, 2, 3, 4]]
2 [[1], [2, 3, 4]]
3 [[1, 2], [3, 4]]
4 [[1, 3, 4], [2]]
5 [[1], [2], [3, 4]]
6 [[1, 2, 3], [4]]
7 [[1, 4], [2, 3]]
8 [[1], [2, 3], [4]]
9 [[1, 3], [2, 4]]
10 [[1, 2, 4], [3]]
11 [[1], [2, 4], [3]]
12 [[1, 2], [3], [4]]
13 [[1, 3], [2], [4]]
14 [[1, 4], [2], [3]]
15 [[1], [2], [3], [4]]
However, the size of each element of each partition should not exceed k = 2. All the case where any subset has more than k=2 elements should be deleted. Therefore, the result should be as follows:
3 [[1, 2], [3, 4]]
5 [[1], [2], [3, 4]]
7 [[1, 4], [2, 3]]
8 [[1], [2, 3], [4]]
9 [[1, 3], [2, 4]]
11 [[1], [2, 4], [3]]
12 [[1, 2], [3], [4]]
13 [[1, 3], [2], [4]]
14 [[1, 4], [2], [3]]
15 [[1], [2], [3], [4]]
Would there be an algorithm in python?
Solution 1:[1]
Filter the result of an answer posted in the link you provided by length. For example with more_itertools.set_partitions if you want to avoid technicality (not in the standard library).
p = [[[1, 2, 3, 4]],
[[1], [2, 3, 4]],
[[1, 2], [3, 4]],
[[1, 3, 4], [2]],
[[1], [2], [3, 4]],
[[1, 2, 3], [4]],
[[1, 4], [2, 3]],
[[1], [2, 3], [4]],
[[1, 3], [2, 4]],
[[1, 2, 4], [3]],
[[1], [2, 4], [3]],
[[1, 2], [3], [4]],
[[1, 3], [2], [4]],
[[1, 4], [2], [3]],
[[1], [2], [3], [4]]]
def filter_partition(partitions, k):
return [p for p in partitions if all(len(block)<=k for block in p)]
print(*filter_partition(p, 2), sep='\n')
Output
[[1, 2], [3, 4]]
[[1], [2], [3, 4]]
[[1, 4], [2, 3]]
[[1], [2, 3], [4]]
[[1, 3], [2, 4]]
[[1], [2, 4], [3]]
[[1, 2], [3], [4]]
[[1, 3], [2], [4]]
[[1, 4], [2], [3]]
[[1], [2], [3], [4]]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | cards |
