Do you need help?

Notice Board

Per partecipare al corso di Fondamenti di programmazione 2021-22 loggatevi e attivatelo nella vostra pagina dei corsi preferiti. A quel punto il corso appare nel menĂ¹ personale cliccando sul proprio avatar. Per i materiali degli anni precedenti seguite lo stesso metodo.

To join the Programming/Lab 2021-22 course, log-on and select it on the my courses page. It will appear on the personal menu of your avatar. For earlier years use the same method.

VIDEOLEZIONI DEL CORSO DI FONDAMENTI DI PROGRAMMAZIONE AA20-21

PROGRAMMING COURSE VIDEOCONFERENCES AY20-21

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

N
Nicholas Tiveron (1710 points)
2 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.

209 views
closed

1 Answer

Best answer
b
benjamin (2490 points)
0 6 21
by (2.5k points)
selected by
Try

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

(Instead of commas put plus)
N
Nicholas Tiveron (1710 points)
2 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.