def test(i,j):
if(i==0):
return j
else:
return test(i-1,i j)
print(test(4,7))
I understand that i=4 and 4 is not equal to zero, therefore the second condition is executed but how does "test(i-1,i j) work? Do you substitute i and j? eg. (3-1,3 7)? Can someone please clarify this for me as I am highly confused.
CodePudding user response:
this is called a recursive function, you might notice that the function calls itself. Usually those functions have base conditions, which will stop the recursion, in your case, it's when i reaches zero. But be careful: if you start with a negative value for i, you won't reach the base condition, since i is getting decreased by one in each call: e.g.: let's say i=-1 and j=10 => test(-1,10)
test(-1,10): i is not equal to zero, therefore else block is applied:
test(i-1, i j) -> test(-1-1, -1 10) -> test(-2, -9)
test(-2, -9): i is not equal to zero, therefore else block is applied:
test(i-1, i j) -> test(-2-1, -2 9) -> test(-3, -7)
test(-3, -7)
... as you can see, i get's decremented in each call and ONLY stops when i is equal to zero.
This also explained the logic of the recursive function:
test(4,7) -> return test(3,11)
-> return test(2,14)
-> return test(1,16)
-> return test(0, 17)
-> return 17 (base condition is reached, i==0)
Now, the recursion goes backwards and the 17 is returned to the first call.
CodePudding user response:
As suggested by @AdroMine, you can modify your function to print the values of i
and j
before each recursive call to test()
:
def test(i, j):
print(f'i = {i} j = {j}')
if (i == 0):
return j
else:
return test(i-1, i j)
Calling test(4, 7)
would result in:
i = 4 j = 7
i = 3 j = 11
i = 2 j = 14
i = 1 j = 16
i = 0 j = 17
This function calculates the sum of j
and i
, i-1
, i-2
, ..., 1
.
how does "test(i-1,i j) work?
At every call:
- The value of
i
is decremented by1
, then passed as a first argument. - The value of
j i
is calculated, then passed as a second argument (returned wheni
is equal to0
).
In other words:
- The first parameter
i
serves the purpose of the loop counter. - The second parameter
j
serves the purpose of holding the sum.
To better clear things, you can write an iterative version of test()
:
def test2(a, b):
j = b
for i in range (a, 0, -1):
j = i
return j