Please ignore secret bonuses. Secret tests do NOT award bonus. Max hw grade is 30+2 bonus efficiency

Do you need help?

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

N
Nicholas Tiveron (1710 points)
4 5 8
in Programming in Python by (1.7k points)
recategorized by

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.

521 views
closed

1 Answer

Best answer
b
benjamin (2490 points)
1 7 21
by (2.5k points)
selected by
Try

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

(Instead of commas put plus)
N
Nicholas Tiveron (1710 points)
4 5 8
by (1.7k 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.