I have a function which is called recursively and I want to know the current level of recursion. Below code shows the method that I am using to calculate it, but it is not giving the expected results.
E.g. : To find the recursion level for a system path:
import os funccount = 0 def reccount(src): global funccount print "Function level of %s is %d" %(src, funccount) def runrec(src): global funccount funccount = funccount + 1 lists = os.listdir(src) if((len(lists) == 0)): funccount = funccount - 1 reccount(src) for x in lists: srcname = os.path.join(src, x) if((len(lists) - 1) == lists.index(x)): if (not(os.path.isdir(srcname))): funccount = funccount - 1 if os.path.isdir(srcname): runrec(srcname) runrec(C:\test)
Problem : Given a directory path, print the level of recursion for directory
Directory Structure is : In my directory structure, i will call the function "reccount(Test)" (Function will be called with path to MainFolder). I want to know the level of recursion call for each folder. (Directory only)
Test: |----------doc |----------share |----------doc |----------file1 |----------bin |----------common |----------doc |----------extras |----------file2
When i call the procedure, i get the following result:
Function level of C:\test is 1 Function level of C:\test\bin is 2 Function level of C:\test\bin\common is 3 Function level of C:\test\bin\common\doc is 3 Function level of C:\test\doc is 3 Function level of C:\test\extras is 3 Function level of C:\test\share is 4 Function level of C:\test\share\doc is 5
As you can see, when it prints results for bin/common/doc, it prints 3 instead of 4 and all subsequent results are wrong
Use the getrecursionlimit() Function to Get the Maximum Recursion Depth in Python.
Python's default recursion limit is 1000, meaning that Python won't let a function call on itself more than 1000 times, which for most people is probably enough. The limit exists because allowing recursion to occur more than 1000 times doesn't exactly make for lightweight code.
Every time a function enters another level of recursion an extra frame is added to the call stack. In order to process the frame an area of memory has to be allocated. Eventually the memory allocated for recursion is exhausted and the Recursive Depth Limit is reached.
Thus in our case, the number of recursive calls is n0 +n2 = 2n0 −1, which means that the total number of recursive calls is equal to 2Fn+1 − 1. This way, we have reached the same result with [2], however, in a much simpler way from the mathematical and pedagogical point of view.
def some_method(data, level=0): some_method(..., level=level+1) if __name__ == '__main__': some_method(my_data)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With