Skip to content Skip to sidebar Skip to footer

Retrieve All Possible Combinations Of Ascending Integers From Sublists

I have lists containing sublists. From theses lists I want to retrieve all combinations of integers that are in ascending order. Also the order of the sublists is important (see ex

Solution 1:

Use itertools.combinations and itertools.product. This is not an efficient solution, as this was not a requirement. Making this more efficient (i.e. using backtracking) will take quite some work, and still in theory it can't go below 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], [0], [4], [2], [5]]
a3 = [[0], [1, 4], [2]]


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

out:

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

Post a Comment for "Retrieve All Possible Combinations Of Ascending Integers From Sublists"