gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 07:31:14 25 4
gpt4 key购买 nike

我有包含子列表的列表。从这些列表中,我想检索所有按升序排列的整数组合。子列表的顺序也很重要(请参阅预期输出)。
当函数本身也返回整数时,这并不是一件坏事(请参阅预期输出中的可选子列表)。
此外,当子列表具有多个值时,我也想将它们视为单独的组合。这些值不能同时出现(参见示例 3)。

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

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

example_list3 = [[0], [1, 4], [2]]
get_ascending_sublist_values(example_list3)
>> [[0, 1, 2], [0, 1], [0, 4], [0, 2], [1, 2], (optional: [1], [0], [4], [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], [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)

出去:
{(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)}

关于python - 从子列表中检索升序整数的所有可能组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67920773/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com