📜  用Python理解递归函数

📅  最后修改于: 2022-05-13 01:55:18.284000             🧑  作者: Mango

用Python理解递归函数

递归的特征是根据自身描述某事物的过程;换句话说,它是自己为函数命名的过程。递归是函数直接或隐式调用自身的机制,产生的函数称为递归函数

好处:

  • 代码可重用性
  • 通俗易懂
  • 时间复杂度有时低
  • 更少的代码

缺点:

  • 如果条件超过则导致溢出
  • 更多内存
  • 很难理解
  • 很难调试
  • 递归中的终止条件是必须的

句法:

递归调用已经被调用的函数,并且会多次调用直到条件变为假。之后,它将返回值

应用:

  • 河内塔
  • 堆栈实现
  • 斐波那契实现
  • 操作系统中的循环问题。

除了上述应用程序之外,下面是一些描述如何在程序中使用递归函数的示例。

示例 1:

打印斐波那契数列到给定项的Python程序。

在这个程序中,值定义在 until_range 变量中,然后我们将该变量传递给一个参数,然后调用递归函数。

recursive_function(a-1) + recursive_function(a-2)

执行:

Python3
# Recursive function
def recursive_function(a):
   
    # Check number
    if a <= 1:
        return a
    else:
         
        # Get next term
        return(recursive_function(a-1) + recursive_function(a-2))
 
     
# Display first fibonacci number
print("\nFibonacci series upto 1 number:")
for i in range(1):
    print(recursive_function(i),
          end=" ")   
     
# Display first 5 fibonacci numbers
print("\nFibonacci series upto 5 numbers:")
for i in range(5):
    print(recursive_function(i),
          end=" ")
     
# Display first 10 fibonacci numbers
print("\nFibonacci series upto 10 numbers:")
for i in range(10):
    print(recursive_function(i),
          end=" ")


Python3
# recursive function
def recursion_factorial(a):
   
    # check number
    if a == 1:
        return 1
    else:
         
        # multiply with next number
        return (a * recursion_factorial(a-1))
 
 
# factorial of 7
n = 7
print("Factorial of", n, "is", recursion_factorial(n))
 
# factorial of 2
n = 2
print("Factorial of", n, "is", recursion_factorial(n))
 
# factorial of 4
n = 4
print("Factorial of", n, "is", recursion_factorial(n))
 
# factorial of 9
n = 9
print("Factorial of", n, "is", recursion_factorial(n))
 
# factorial of 10
n = 10
print("Factorial of", n, "is", recursion_factorial(n))


输出:

Fibonacci series upto 1 number:
0 
Fibonacci series upto 5 numbers:
0 1 1 2 3 
Fibonacci series upto 10 numbers:
0 1 1 2 3 5 8 13 21 34 

示例 2:

用于查找数字阶乘的Python程序。

在这个Python程序中,我们将返回一个整数的阶乘。我们将变量 n 值传递给参数,然后调用函数。

a* recursion_factorial(a-1)

执行:

蟒蛇3

# recursive function
def recursion_factorial(a):
   
    # check number
    if a == 1:
        return 1
    else:
         
        # multiply with next number
        return (a * recursion_factorial(a-1))
 
 
# factorial of 7
n = 7
print("Factorial of", n, "is", recursion_factorial(n))
 
# factorial of 2
n = 2
print("Factorial of", n, "is", recursion_factorial(n))
 
# factorial of 4
n = 4
print("Factorial of", n, "is", recursion_factorial(n))
 
# factorial of 9
n = 9
print("Factorial of", n, "is", recursion_factorial(n))
 
# factorial of 10
n = 10
print("Factorial of", n, "is", recursion_factorial(n))

输出:

Factorial of 7 is 5040
Factorial of 2 is 2
Factorial of 4 is 24
Factorial of 9 is 362880
Factorial of 10 is 3628800