简体   繁体   English

如何在Python的递归函数的结尾处返回列表

[英]How to return a list on the end of a recursive function in Python

I was playing with the fibonacci sequence in Python (I know the implementation with yield, but wanted to implement it with recursion) and ended up with the following code snippet: 我正在使用Python中的fibonacci序列(我知道yield的实现,但想通过递归实现),并得到以下代码片段:

def fib(start, leng):
    """ Recursive Fibbo"""
    # Should be lists
    if type(start) == int:
        start = [start]

    # Escape route
    if len(start) == leng:
        print start
        return start

    # Run
    else:
        if int(start[-1]) == 0:
            start.append(1)
        else:
            if len(start) == 1:
                start.append(start[-1])

        next_number = int(start[-1]) + int(start[-2])
        start.append(next_number)
        fib(start, leng)

Now, it works like this: 现在,它的工作方式如下:

>>> a = fib(0, 10)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
>>> type(a)
<type 'NoneType'>
>>> 

It calculates the sequence, and in the end print it... But... How I could do to it return the list as well? 它计算序列,最后打印出来。。。。。。。。。。。。。。。。。。

Is it possible to do without any other helper function nor using yield not any external lib? 是否可以在没有任何其他辅助函数的情况下,也可以在没有任何外部库的情况下使用yield?

If not, why? 如果没有,为什么? (and if yes, how)? (如果是,如何)?

Thanks! 谢谢! :) :)

Just change the last line to 只需将最后一行更改为

 return fib(start,  leng)

This will go down the line of the recursion to do the "next bit" of work and return the final product that is based on your base case defined earlier in your code as your escape route: 这将在递归行中完成“下一部分”工作,并返回基于您先前在代码中定义的基本情况的最终产品作为逃生路线:

# Escape route
if len(start) == leng:
    print start
    return start

Once you hit the return in your escape route, the return gets propagated back up the call stack, each call to return fib(start, leng) returning up to itself the complete answer. 一旦在逃生路线中击中了返回,返回return fib(start, leng)传播回调用堆栈,每个return fib(start, leng)调用将return fib(start, leng)完整的答案。 Once the call stack is back in your original call to the function (made elsewhere), the function actually completes and returns your expected value. 一旦调用堆栈返回到对函数的原始调用(在其他地方进行),该函数实际上就会完成并返回您的期望值。

Your last line also needs to be a return : 您的最后一行也需要return

return fib(start, leng)

Without that, your return value from the "escape route" is not propagated back. 否则,您的“转义路线”返回值将不会传播回来。

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

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