Recursion in for loop python
I have a database that models a foldering relationship to Show Assuming I have a function called The following code works for 4 levels of nesting, but I'd like more flexibility in either specifying the depth of recursion, or in intelligently stopping the loop when there are no more children to follow.
asked Nov 9, 2010 at 21:31
1 A recursive function is a nice way to do this:
answered Nov 9, 2010 at 21:39
Jochen RitzelJochen Ritzel 101k29 gold badges195 silver badges190 bronze badges 6 I generally avoid recursion like the plague in python because it's slow and because of the whole stack overflow error thing.
This assumes that answered Nov 9, 2010 at 21:43
aaronasterlingaaronasterling 66.6k20 gold badges123 silver badges125 bronze badges 1
answered Nov 9, 2010 at 21:34 2 This is the closest to your code, and very unpythonic:
You should probably look for answered Nov 9, 2010 at 21:40
LloekiLloeki 6,4132 gold badges30 silver badges32 bronze badges 4 I needed something similar once to check a hierarchic tree. You could try:
answered Sep 22, 2014 at 18:33
pedrovgppedrovgp 6758 silver badges23 bronze badges Not the answer you're looking for? Browse other questions tagged python loops recursion nested or ask your own question.Can you use recursion in a for loop?You surely can use loops in a recursive function. What makes a function recursive is only the fact that the function calls itself at some point in its execution path. However you should have some condition to prevent infinite recursion calls from which your function can't return.
What is a recursive loop in Python?Python also accepts function recursion, which means a defined function can call itself. Recursion is a common mathematical and programming concept. It means that a function calls itself. This has the benefit of meaning that you can loop through data to reach a result.
Can we use loops to implement recursion in Python?Practical Applications of Recursion
Problems that can be solved with recursion, most likely can be solved with loops.
Which is better for loop or recursion?Recursion has more expressive power than iterative looping constructs. I say this because a while loop is equivalent to a tail recursive function and recursive functions need not be tail recursive. Powerful constructs are usually a bad thing because they allow you to do things that are difficult to read.
|