Python中的递归函数 [英] Recursion function in Python

查看:44
本文介绍了Python中的递归函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑 Python 中的这个基本递归:

Consider this basic recursion in Python:

def fibonacci(number):
    if number == 0: return 0
    elif number == 1:
        return 1
    else:
        return fibonacci(number-1) + fibonacci(number-2)

根据斐波那契数列的 (n-1) + (n-2) 函数,这是有道理的.

Which makes sense according to the (n-1) + (n-2) function of the Fibonacci series.

Python 如何执行包含不在同一代码行内而是在同一代码行内的另一个递归的递归?'finobacci(number-1)' 是否完成了所有的递归,直到它达到 '1' 然后它对 'fibonacci(number-2)' 执行相同的操作并将它们相加?

How does Python execute recursion that contains another recursion not within but inside the same code line? Does the 'finobacci(number-1)' complete all the recursion until it reaches '1' and then it does the same with 'fibonacci(number-2)' and add them?

为了比较,以下递归函数用于将数字 'x' 提升为幂 'y',我可以理解递归, def power 调用自身直到 y==0 ,因为在一行中只有一个递归调用.仍然不应该所有结果都是1",因为当 y==0 时执行的最后一个命令是返回 1",因此不返回 x?

For comparison, the following recursive function for raising a number 'x' into power 'y', I can understand the recursion, def power calling itself until y==0 , since there's only one recursive call in a single line. Still shouldn't all results be '1' since the last command executed is 'return 1' when y==0, therefore x is not returned?

def power(x, y):
    if y == 0:
        return 1
    else:
        return x*power(x, y-1)

推荐答案

在表达式 fibonacci(number-1) + fibonacci(number-2) 中,第一个函数调用必须在调用第二个函数调用.

In the expression fibonacci(number-1) + fibonacci(number-2) the first function call will have to complete before the second function call is invoked.

因此,第一次调用的整个递归堆栈必须在第二次调用开始之前完成.

So, the whole recursion stack for the first call has to be complete before the second call is started.

这篇关于Python中的递归函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆