Python Recursive function introduction
Yun Zhengjie
Copyright Notice: Original works, declined reprint! Otherwise, the legal liability will be investigated.
I. How recursive functions work
1. Case Show
1 #! /usr/bin/env python2 #_*_coding:utf-8_*_3 #@author: Yinzhengjie4 #blog:http://www.cnblogs.com/yinzhengjie/tag/python%e8%87%aa%e5%8a%a8%e5%8c%96%e8%bf%90%e7%bb%b4%e4%b9%8b% e8%b7%af/5 #Email:[email protected]6 7 8 ImportSYS9 #print (dir (sys))Ten #sys.setrecursionlimit (1000000) #修改默认递归调用的次数, it is not recommended to modify! One #print (Sys.getrecursionlimit ()) #查看递归函数的最大可以调用的次数, by default it can be called 1000 times; A - - defAge (n): the ifn = = 5:#Specify a definite recursive end condition; - return18 - returnAge (N+1) +2 - + - Print(Age (1)) + A """ at Recursive functions: - 1> The recursive function must have a definite end condition - recursive functions are inefficient and need to be left in the current state at the next recursion, the workaround being the tail recursion, which is the last step in the function - (rather than the last line) calls itself, but Python has no tail recursion and limits the recursive hierarchy. - 2> each time a deeper level of recursion is reached, the problem size should be reduced compared to the previous recursion; - 3>: Recursive efficiency is not high, too many recursive levels will lead to stack overflow; in - """ to + - the * #The result of the above code execution is as follows: $26
2. Graphical Recursive functions
Two. Small trial sledgehammer
1 #! /usr/bin/env python2 #_*_coding:utf-8_*_3 #@author: Yinzhengjie4 #blog:http://www.cnblogs.com/yinzhengjie/tag/python%e8%87%aa%e5%8a%a8%e5%8c%96%e8%bf%90%e7%bb%b4%e4%b9%8b% e8%b7%af/5 #Email:[email protected]6 7 8 9 Ten defPiercingeye (List): One forIteminchList: A ifisinstance (item, list): - Piercingeye (item) - Else: the Print(item) - - -ListNum = [1, [2, 3, [4, [5, 6, 7, [8, 9]]]]] + Piercingeye (ListNum) - + A at - #The result of the above code execution is as follows: -1 -2 -3 -4 in5 -6 to7 +8 -9
Python Recursive function introduction