简体   繁体   English

为什么我的递归函数不接受第二个参数?

[英]Why is my recursive function not taking a 2nd argument?

"""

def permNums(inp,sec):
    newInp = []
    for i in inp:
        for j in sec:
            if j not in i: newInp.append( i+j )      #I put the print after this line
    return newInp


b = permNums(permNums(permNums(inp='word',sec='word')))

print b
"""


def permNums(inp):
    newInp = []
    for i in inp:
        for j in 'word':
            if j not in i: newInp.append( i+j )
    return newInp


b = permNums(permNums(permNums(inp='word')))

print b

The way I see it the code that has been commented out and the one that has not, should be equivalent. 我看到它的方式应该与被注释掉的代码和未被注释的代码等效。 The commented out code throws me an error saying i've only given 1 argument instead of 2. Where am I going wrong? 注释掉的代码使我出错,说我只给出了1个参数而不是2个参数。我在哪里出错?

I tried putting a print function right after 我尝试在之后放置打印功能

 if j not in i: newInp.append( i+j )

,in the commented out code and noticed that the innermost function does get called but then gives an error at the 2nd recursion possibly because it doesnt take 'sec' as an argument.. Can someone clear this out for me please. ,在注释掉的代码中,注意到最里面的函数确实被调用,但是在第二次递归时给出了错误,可能是因为它没有以“ sec”作为参数。。有人可以帮我清除这个吗?

The problem comes from the second call. 问题来自第二个电话。 Let me illustrate it. 让我说明一下。 When the result of the inner call is returned, Python then has to do this one: 返回内部调用的结果后,Python必须执行以下操作:

permNums(result_of_previous_call)  # sec won't implicitly carry through.

which is obviously only one argument. 这显然只是一个论点。 Therefore to fix the commented-out one, you need to supply the extra sec argument for each call: 因此,要解决已注释掉的问题,您需要为每个调用提供额外的sec参数:

b = permNums(permNums(permNums(inp='word', sec='word'), sec='word'), sec='word')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM