python3 example of recursion

First, the use of recursion: 1 + 2 + 3 + 4 + 5 ... + n and the first n items
. 1  DEF recursion_sum_1 (n-):
 2      # when n = 1; and 1 
. 3      # Otherwise, n for and equivalent to the + n-(n--1) 
. 4  
. 5      IF n-==. 1 :
 . 6          return . 1
 . 7  
. 8      the else :
 . 9          return recursion_sum_1 + n-(. 1-n- )
 10  
. 11  Print (recursion_sum_1 (100))         # 5050

Second, the use of recursive evaluation: 1-2 + 3-4 + 5 ... + n and the first n items

. 1  DEF recursion_sum_2 (n-):
 2      # when n = 1; and 1 
. 3      # Otherwise, n for and equivalent to the + n-(n--1) 
. 4      IF n-==. 1 :
 . 5          return . 1
 . 6      the else :
 . 7          IF n-% == 2 0:
 . 8              return -n + recursion_sum_2 (n--. 1 )
 . 9          elif n-% 2 =! 0:
 10              return n-recursion_sum_2 + (n--. 1 )
 . 11  
12 is  Print (recursion_sum_2 (. 4))     # -2

note:

Advantages and disadvantages of recursive : 
Advantages:
simplification of the problem, make ideas more clearly, the code is more concise
Cons:
Recursive system due to large environmental impact, when the recursion depth is too large, unpredictable results might occur

Guess you like

Origin www.cnblogs.com/gengyufei/p/11316289.html