首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

用于生成两个相同列表(包括不完整列表)的所有组合的脚本

生成两个相同列表的所有组合的脚本可以使用递归的方式来实现。下面是一个示例的Python脚本:

代码语言:txt
复制
def generate_combinations(list1, list2, prefix=[]):
    if len(list1) == 0 and len(list2) == 0:
        print(prefix)
        return

    if len(list1) > 0:
        generate_combinations(list1[1:], list2, prefix + [list1[0]])
    
    if len(list2) > 0:
        generate_combinations(list1, list2[1:], prefix + [list2[0]])

list1 = [1, 2, 3]
list2 = [4, 5]

generate_combinations(list1, list2)

这个脚本会输出两个列表的所有组合,例如对于输入的list1 = [1, 2, 3]list2 = [4, 5],输出结果为:

代码语言:txt
复制
[1, 2, 3, 4, 5]
[1, 2, 3, 5, 4]
[1, 2, 4, 3, 5]
[1, 2, 4, 5, 3]
[1, 2, 5, 3, 4]
[1, 2, 5, 4, 3]
[1, 4, 2, 3, 5]
[1, 4, 2, 5, 3]
[1, 4, 3, 2, 5]
[1, 4, 3, 5, 2]
[1, 4, 5, 2, 3]
[1, 4, 5, 3, 2]
[1, 5, 2, 3, 4]
[1, 5, 2, 4, 3]
[1, 5, 3, 2, 4]
[1, 5, 3, 4, 2]
[1, 5, 4, 2, 3]
[1, 5, 4, 3, 2]
[2, 1, 3, 4, 5]
[2, 1, 3, 5, 4]
[2, 1, 4, 3, 5]
[2, 1, 4, 5, 3]
[2, 1, 5, 3, 4]
[2, 1, 5, 4, 3]
[2, 3, 1, 4, 5]
[2, 3, 1, 5, 4]
[2, 3, 4, 1, 5]
[2, 3, 4, 5, 1]
[2, 3, 5, 1, 4]
[2, 3, 5, 4, 1]
[2, 4, 1, 3, 5]
[2, 4, 1, 5, 3]
[2, 4, 3, 1, 5]
[2, 4, 3, 5, 1]
[2, 4, 5, 1, 3]
[2, 4, 5, 3, 1]
[2, 5, 1, 3, 4]
[2, 5, 1, 4, 3]
[2, 5, 3, 1, 4]
[2, 5, 3, 4, 1]
[2, 5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, 2, 1, 4]
[5, 3, 2, 4, 1]
[5, 3, 4, 1, 2]
[5, 3, 4, 2, 1]
[5, 4, 1, 2, 3]
[5, 4, 1, 3, 2]
[5, 4, 2, 1, 3]
[5, 4, 2, 3, 1]
[5, 4, 3, 1, 2]
[5, 4, 3, 2, 1]

这个脚本会生成两个列表的所有可能组合,并将结果打印出来。注意,这个脚本的时间复杂度为O(2^n),其中n为两个列表的长度之和。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

10分19秒

day20/下午/398-尚硅谷-尚融宝-生成所有回款计划列表的业务实现

27分40秒

day20/下午/399-尚硅谷-尚融宝-生成一条投资记录的所有回款计划列表

6分41秒

2.8.素性检验之车轮分解wheel factorization

5分12秒

2.7.素性检验之孙达拉姆筛sieve of sundaram

领券