【问题标题】:python tail recursive function doesn't returnpython尾递归函数不返回
【发布时间】:2015-11-09 15:20:07
【问题描述】:

我有一个修改列表的函数,但它不返回任何内容。这是一个很长的函数,但举个例子,下面有同样的问题。为什么没有返回任何东西?

def inventedfunction(list1):
    list2=list1[:-1]
    if len(list2)!=1:
        inventedfunction(list2) 
    else:
        return list2  

【问题讨论】:

  • 因为inventedfunction(list2) 的意思是'调用list2上的发明函数,但丢弃它的结果'。我猜你需要return inventedfunction(list2)
  • 如果我需要在这个例子中使用递归,我该如何避免这个问题?

标签: python recursion return


【解决方案1】:

inventedfunction(list2) 替换为return inventedfunction(list2)。如果只调用它而不带return语句,结果会被抛出。

工作代码:

def inventedfunction(list1):
    list2=list1[:-1]
    if len(list2)!=1:
        return inventedfunction(list2) 
    else:
        return list2 

【讨论】:

  • 谢谢。如果我在运行发明函数(somelist) 后需要修改输入列表(somelist) 怎么样?
  • somelist = inventedfunction(somelist)
【解决方案2】:

你没有说函数应该做什么,所以我假设“inventedfunction”的意思是“inverted function”。即使这不正确,但想法是相同的。如果不是这种情况,或者您不明白,请回复更多信息。

如果 len(list2) != 1,您不会收到任何返回,并且不会返回任何内容 (None)。您还必须创建第二个列表来保存从发送到的列表中删除的数字函数,并根据代码的结构方式返回更新后的列表。

def inventedfunction(list1, new_list=[]):
    ## at the least add print statements so you know what is happening
    print new_list, "----->",  list1
    list2=list1[:-1]
    new_list.append(list1[-1])  ## append item removed from list1 --> list2
    if len(list2):
        new_list, list2=inventedfunction(list2)
    return new_list, list2  ## both updated lists returned

print inventedfunction([1, 2, 3, 4, 5])

【讨论】:

    猜你喜欢
    • 2016-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-12
    • 2015-10-22
    • 1970-01-01
    相关资源
    最近更新 更多