Definition: Inside a function, other functions can be called. If a function calls itself internally, the function is a recursive function.
Factorial instances
1 n = Int (input (">>:"))234def F (n):5 s = 16 for in range (2, (n + 1)): 7 s *= i8 return s9Print (f (n))
Recursive
1 def factorial_new (n): 2 3 if n==1:4 return 15 return n*factorial_new ( N-1)6 7print(factorial_new (3))
Features of recursive functions:
1 calling its own function
2 There is an obvious end condition, the problem size decreases compared to the last recursion
Advantages: Simple definition, clear logic, all recursive functions can be written in a circular way, but the logic of the loop is not as clear as recursion.
However, the efficiency of recursion is not high, too many recursive levels will lead to stack overflow, about 1000 layers.
Fibonacci sequence
1 defFibnum (n):#Fibonacci Sequence2A, b = 0, 13 forIinchrange (n):4B, a = a +B, b5 returnb6n = Int (input (">>:"))7 ifn = = 1:8 Print(0)9 elifn = = 2:Ten Print(1) One Else: A Print(Fibnum (n-2))
Write with recursion
1 defFibo (n):2Before =03after = 14 ifn = = 0orn = = 1:5 returnN6 7 ifN <= 3:8 return19 returnFibo (n-1) +fibo (n-2)Ten One Print(Fibo (3))
Recursive efficiency is low, when the number is too large, it will be very slow.
Python recursive function and Fibonacci sequence