How to add to a counter when calling the same function recursively many times

N
Nicholas Tiveron (1670 points)
2 5 8
asked Jan 24, 2021 in Programming in Python by Nicholas Tiveron (1,670 points)
recategorized Jan 25, 2021 by andrea.sterbini

Hello everybody! 

Since I've been working on this specific problem for a few days now: is there a way to call the same function recursively multiple times (and add to the same counter)? I'll make an example (as generic as possible) to clarify:

def  recursion(variable_name,  counter=0):

...

counter += 1

if ...:

return counter

else:

return  recursion(a, counter), recursion(b, counter), recursion(c, counter), recursion(d, counter)

With this function, the output should ultimately be an integer but what I get is something like this instead: 

(((1, 1, 1, 1), 1, 1, (1, 1, (1, 1, 1, 1))), 1, 1)

where the number of 1s sums up to the integer I'm expecting (and the number of 1s inside the same tuple correctly represents the number of rectangles and sub-rectangles I'm counting inside the given image). 

Of course, if I try to do

  [return etc.]

 lists and sub-lists are created instead of tuples (this is to say that I didn't decide to make them, they are automatically created). 

I get this same type of result no matter the input image (so it's not an issue with a particular case/test). Moreover, I have checked in different ways and it seems that the recursion actually does what it's supposed to and accurately counts all the rectangles, so it's just a problem of the counter being "separated" from the others instead of being summed with each repetition (I thought passing the counter as an argument would solve this problem but clearly it doesn't). The purpose of this function is to check every variable / piece of land (= rectangle), which can have other four variables / pieces of land inside it and so on, and add 1 to the counter if certain conditions are met. 

I tried my best to explain it in a general way so that even people that are not familiar with this assignment can suggest possible solutions. Any help is much appreciated.

125 views

1 Answer

Best answer
b
benjamin (2490 points)
0 6 21
answered Jan 24, 2021 by benjamin (2,490 points)
selected Jan 24, 2021 by Nicholas Tiveron
Try

Return Recursion(a,...) + recursion(b,...)

(Instead of commas put plus)
N
Nicholas Tiveron (1670 points)
2 5 8
commented Jan 24, 2021 by Nicholas Tiveron (1,670 points)
Wow, that never passed through my mind. It was such an easy thing to fix and I was completely stuck. Thank you so much.