+ 1

Please help why are x and y being added together ? What am I missing

def rec(x,y): if x == 0: return y: if y != 0: return rec( x-1, y+1) print(rec(3,4)) # Output is 7 # why is it not (2,5)

28th Oct 2022, 8:10 AM
Steven kervick
Steven kervick - avatar
11 Respostas
+ 7
It is a recursive function (it calls itself). It has two arguments. If the first argument x is zero, the result is the other argument. Otherwise x is decreased and y is increased, and the function is called with these new numbers again. What happens effectively: rec(3, 4) = rec(2, 5) = rec(1, 6) = rec(0, 7) = 7 is returned through the call stack
28th Oct 2022, 8:31 AM
Tibor Santa
Tibor Santa - avatar
+ 5
Recursion is a tricky topic, I see you are doing the Python Beginner course and this is covered in the intermediate course. Return is giving back a value to the place where the function was called. But in this case, the last line of the function returns a new invocation of the same function, which is yet to be calculated with the new values. This could go on forever, but in recursion we always have a "base case" which is supposed to stop this endless loop. In this one, the recursion is stopped when either X or Y reach 0.
28th Oct 2022, 8:49 AM
Tibor Santa
Tibor Santa - avatar
+ 2
O ok thanks I thought it was adding the two numbers 2 and 5. Also I thought you needed while or for to loop. Does the return start the sequence again. Your help is much appreciated I am very new to all this.
28th Oct 2022, 8:39 AM
Steven kervick
Steven kervick - avatar
+ 2
Thank you for your help. I understand it now. Its quite simple once I read it again. 👍
29th Oct 2022, 6:13 AM
Steven kervick
Steven kervick - avatar
+ 2
Because you return the def rec ,it will start the code again and again. It will go on forever until x or y is == 0.the function calls itself.. maybe someone more advanced could explain it better.
29th Oct 2022, 11:44 AM
Steven kervick
Steven kervick - avatar
+ 1
I can't understand that can you explain it !!!!
29th Oct 2022, 11:38 AM
Raju
Raju - avatar
+ 1
Each time X will -1 and y will + 1. It will stop once either == 0
29th Oct 2022, 11:47 AM
Steven kervick
Steven kervick - avatar
0
def rec(x,y): if x == 0: return y # remove ":" (The colon) if y != 0: return ( x-1, y+1) # remove "rec" print(rec(3,4))
28th Oct 2022, 8:17 AM
SoloProg
SoloProg - avatar
0
Sorry the : after return was a misprint. It still adds X and y together. I am just not sure why
28th Oct 2022, 8:22 AM
Steven kervick
Steven kervick - avatar
0
Why does putting the rec after the return add X and y
28th Oct 2022, 8:24 AM
Steven kervick
Steven kervick - avatar
0
Ello
29th Oct 2022, 3:46 PM
Leo Monnat