Below, is a simplified version of the original code I posted. When the code runs, it goes through its first iteration of the for loop, finds an element that meets the condition (the first element )and calls another instance of the function. NOTE: In my understanding of recursion, the first instance of the function has 'frozen' awaiting to iterate to the next element once the 2nd instance of the function has completed, popping off the call stack However when the 2nd instance of the function finishes, the first instance of the function does not resume. why?? What am I missing here??
class Solution:
def main(self,x,y):
self.directions = [(-1, 0), (0, -1), (1, 0), (0,1)]
self.changed = {}
self.func_count = 0
self.helper(x,y)
def helper(self, x, y):
self.func_count = 1
print("func count ", self.func_count)
for i, j in self.directions:
print("for loop in func count", self.func_count)
# here is the problem. Once a x i, y j meets the below
# conditon, the self.helper func runs and never
# comes back to finish the iteration.. why??
print("x i, y j", x i, y j)
if x i == 0 and y j == 0:
if (x i,y j) not in self.changed:
x = x i
y = y j
self.helper(x,y)
S = Solution()
S.main(0,1)
CodePudding user response:
Your code always refer to self.func_count
, which is the same for all recursive calls~(i.e., every function call increments and overwrites the same copy of func_count
). Thus, it looks like the function never resumes.
You can fix this by defining a local_func_count
:
self.func_count = 1
local_func_count = self.func_count
and using it:
print("for loop in func count", local_func_count)
There's another potential bug in your code: self.changed
is never updated.