gpt4 book ai didi

python - Python 中可变数量的参数和递归

转载 作者:行者123 更新时间:2023-12-01 04:59:11 25 4
gpt4 key购买 nike

我想编写一个递归函数,它接受可变数量的参数(每个参数都是一个可迭代的列表或集合)并返回每个参数的所有串联组合的集合。我学会了如何write functions with a variable number of arguments我知道如何编写递归函数,但我不知道如何在 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:] ) 。我在这里想做的是将除第一个参数之外的所有原始参数传递给函数(从而创建递归)。这显然不是这样做的方法。我的问题:这可以做到吗?如何做到?

Ps:我知道我可以使用带有一个参数的列表列表来完成相同的任务,但我很好奇这是可能的。

最佳答案

请求的工作由以下几行完成:

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

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

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']

希望您喜欢这个;)

亚瑟。

关于python - Python 中可变数量的参数和递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26670968/

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