Python中的可变参数和递归

2 投票
1 回答
3944 浏览
提问于 2025-04-30 20:18

我想写一个递归函数,这个函数可以接收可变数量的参数(每个参数都是一个可迭代的列表或集合),并返回所有参数的连接组合的集合。我学会了如何写可以接收可变数量参数的函数,也知道怎么写递归函数,但我不知道怎么把这两者结合起来在Python中使用(或者说这是否可能)。

这是我的代码:

def generate_combinations( *args ):
    # returns all combinations of each of the arguments
    if len( args ) == 1:
        return set( args[0] )

    result = set()
    lastdigits = generate_combinations( args[1:] )
    for d in args[0]:
         result.add( d + lastdigits )      

if __name__ == '__main__':
    lastDigit = [ '1', '2', '3' ]
    allDigits = [ '4', '5' ]
    print("{}".format( generate_combinations( allDigits, lastDigit )))

期望的输出是:

14
15
24
25
34
35

我代码中的"问题"出现在第7行:lastdigits = generate_combinations( args[1:] )。我想在这里做的是,把所有原始参数除了第一个以外都传递给这个函数(这样就能创建递归)。但显然这不是正确的做法。我的问题是:这能做到吗?如果可以的话,怎么做?

另外,我知道我可以用一个包含列表的列表来实现同样的功能,只用一个参数,但我很好奇这是否真的可能。

暂无标签

1 个回答

4

这些代码行完成了你请求的工作:

args = list(args)
args.pop(0)
recursiveCall( *tuple(args) )

这里你的函数实现有点问题(或者我可能误解了你对集合的使用)。

def generate_combinations( *args, **kwargs ):
    print("called with", args)
    #terminate recursion
    if len(args) == 1:
        return list(set(args[0]))

    #recursion
    else:
        result = []
        args = list(args)
        heads = args.pop(0)
        tails = generate_combinations( *args, **kwargs )
        for head in heads:
            for tail in tails:
                result.append(head + tail)
        return result

if __name__ == '__main__':
    allDigits = [ '1', '2', '3' ]
    lastDigit = [ '4', '5' ]
    letters   = [ 'a', 'b' ]
    print("{}".format( generate_combinations( allDigits, lastDigit, letters , Useless='parameter')))

执行结果是:

['14a', '14b', '15a', '15b', '24a', '24b', '25a', '25b', '34a', '34b', '35a', '35b']

希望你喜欢这个;)

亚瑟。

撰写回答