k = [[1,1,1],[2,2],[3],[4]]
,有大小限制
c = 4
.
然后我想找到所有可能的分区
k
c
. 理想情况下,结果应该是:
[ {[[1,1,1],[3]], [[2,2], [4]]}, {[[1,1,1],[4]], [[2,2], [3]]}, {[[1,1,1]], [[2,2], [3], [4]]}, ..., {[[1,1,1]], [[2,2]], [[3]], [[4]]} ]
我用集合符号的地方
{ }
在上面的例子中(实际情况是
[ ]
我实现了以下算法,但结果不一致:
def num_item(l):
flat_l = [item for sublist in l for item in sublist]
return len(flat_l)
def get_all_possible_partitions(lst, c):
p_opt = []
for l in lst:
p_temp = [l]
lst_copy = lst.copy()
lst_copy.remove(l)
iterations = 0
while num_item(p_temp) <= c and iterations <= len(lst_copy):
for l_ in lst_copy:
iterations += 1
if num_item(p_temp + [l_]) <= c:
p_temp += [l_]
p_opt += [p_temp]
return p_opt
跑步
get_all_possible_partitions(k, 4)
[[[1, 1, 1], [3]], [[2, 2], [3], [4]], [[3], [1, 1, 1]], [[4], [1, 1, 1]]]
一些洞察将会是伟大的!P、 我没有找到类似的问题:/