从子列表中检索升序整数的所有可能组合

问题描述

我有包含子列表的列表。从这些列表中,我想检索所有按升序排列的整数组合。子列表的顺序也很重要(参见预期输出)。

函数本身也返回整数时,这并不是一件坏事(请参阅预期输出中的可选子列表)。

此外,当子列表具有多个值时,我也想将它们视为单独的组合。这些值不能同时出现(参见示例 3)。

example_list = [[1],[0],[4],[2]]
get_ascending_sublist_values(example_list)
>> [[1,4],[1,2],[0,2] (optional: [1],[2])]

example_list2 = [[1],[2],[5]]
get_ascending_sublist_values(example_list2)
>> [[1,4,5],2,[(optional: [1],[5])]

example_list3 = [[0],[2]]
get_ascending_sublist_values(example_list3)
>> [[0,1,1],(optional: [1],[2])]

解决方法

使用 itertools.combinationsitertools.product。这不是一个有效的解决方案,因为这不是必需的。使这更有效(即使用回溯)需要做很多工作,而且理论上它仍然不能低于 o(2^n)

from itertools import combinations
from itertools import product


def get_ascending_sublist_values(a):
    filtered = set()
    for comb_length in range(2,len(a)+1):
        combs = combinations(a,comb_length)

        results = []
        for comb in combs:
            for i in range(len(comb) - 1):
                prods = product(*comb)
                for prod in prods:
                    if sorted(prod) == list(prod):
                        results.append(tuple(sorted(prod)))

        for r in results:
            filtered.add(r)

    print(filtered)


a1 = [[1],[0],[4],[2]]
a2 = [[1],[2],[5]]
a3 = [[0],[1,4],[2]]


get_ascending_sublist_values(a1)
print("----------")
get_ascending_sublist_values(a2)
print("----------")
get_ascending_sublist_values(a3)

出:

{(1,2),(0,(1,4),4)}
----------
{(1,4,5),(4,2,(2,2)}
----------
{(0,1),1,2)}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...