社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

(Python)查找受分区大小限制的列表列表的所有可能分区

Stoner • 6 年前 • 1939 次点击  

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、 我没有找到类似的问题:/

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/53642
文章 [ 2 ]  |  最新文章 6 年前