Recursive
1. 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 (">>:")) 2 3 4 def f (n): 5 s = for i in range (2, (n + 1)): 7 s *= i8 return S9 print ( F (n))
Recursive
1 def factorial_new (n): 2 3 if N==1:4 return return n*factorial_new (n-1) 6 7 print ( 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.
2. Fibonacci Sequence
1 def fibnum (n): #斐波那契数列 2 A, b = 0, 1 3 for I in range (n): 4 B, a = A+b, b 5 return b 6 n = int (input (">>:")) 7 if n = = 1:8 print (0) 9 elif n = = 2:10 print (1) else:12 print (Fibnum (n-2))
Write with recursion
1 def fibo (n): 2 before = 0 3 after = 1 4 if n = = 0 or N = = 1:5 return n 6 7 if n <= 3: 8 return 1 9 return Fibo (n-1) +fibo (n-2) print (Fibo (3))
Recursive efficiency is low, when the number is too large, it will be very slow
Limitations of 3.python recursion
Import Sys
Print (Sys.getrecursionlimit ())
#1000
Sys.setrecursionlimit (10000)
Print (Sys.getrecursionlimit ())
#10000
22-python Basic 11-recursive function