I'm trying to figure out a simple way to handle dynamic nested loops level. Consider the following function that takes in 2 parameters: #num of loops, and max value.
void PrintLoop(int maxloop, int maxvalue)
PrintLoop(1,2);
// output
0
1
PrintLoop(2,2);
// output
0, 0
0, 1
1, 0
1, 1
PrintLoop(3,2);
// output
0, 0, 0
0, 0, 1
0, 1, 0
0, 1, 1
1, 0, 0
1, 0, 1
1, 1, 0
1, 1, 1
Etc...
Is there a way to write a function that can generate this "dynamic nested loops" behavior?
Thanks for any help
Save this answer. Show activity on this post. For CPython 3.7 (and previous CPython versions), the limit is 20.
To implement a dynamic nested loop we need to increment the inner most loop variable until we run out values. Only then do we need to look at changing the upper level loop variables.
Python imposes a limit of 20 nested blocks (not just loops, but this could be loops, or any other static block - including with, try/except and others ).
A loop can be nested inside of another loop. C++ allows at least 256 levels of nesting.
Yes, it is possible, and to implement this a concept of "recursion" is often used:
void PrintLoop(int maxloop, int maxvalue)
{
if (maxloop<=0) return ;
// print something here...
for (int i=0;i<maxvalue;i++){
PrintLoop(maxloop-1, maxvalue);
// After Recursion do something here...
}
}
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