0
How these recursion works?
Hey can anyone explain to me how these recursion works? and what is the solution? i really have no idea thank a lot def charge= (h,k): z = 0 outcome= 0 while z < h: for i in range (z, k+1, 1): if i < 1: outcome = k elif i < 4: outcome = outcome + i else: outcome = outcome + h z = z + 2 return outcome print charge(5,5)
10 Réponses
0
Sal
Because of the last expression in the while loop:
z = z + 2
starting from z=0 (initialized before the while loop)
running for z<h, where h=5 from the function call
so when 6<5 it is false and it does not run anymore
+ 1
check this post.
https://www.sololearn.com/discuss/1149517/?ref=app
+ 1
Matthias
many thanks:)
+ 1
Matthias
aah now i get it. thank you:)
0
This is not a recursion, since the function does not call itself.
I don't really know if this has some real world source, but let's see how to get the value;
z=0
range(0,6,1)
i outcome
0 5
1 6
2 8
3 11
4 16
5 21
z=2
range(2,6,1)
i outcome
2 23
3 26
4 31
5 36
z=4
range(4,6,1)
i outcome
4 41
5 46
z=6
while loop terminated
So it prints 46.
0
hey Matthias,
many thanks. now i understand.
but can you explain how the otcome for z=0; i=4 is 16 ?
And the outcome for z=2; i=5 is 26?
thank you;)
0
Sal
If i equals 4 or is greater than 4, you will get in the else branch.
And there you add +h to your outcome.
Here we have h=5, from the call charge(5,5)
The other was a typo, it should be 36
0
Matthias
hello,
i have a last question. how did you know that you have to repeat z for 0, 2 ,4 to 6?
0
Glad to help :)
0
Matthias
i have a last question. really last question^^
def function (k):
if k<2:
return k
else:
return function(k-1)+function(k-2)
n=8
z=function(n)
print str (z)
solution for this function:
8-1 + 8-2 = 13
7-1 + 5-2 = 9
6-1 + 3-2 = 6
so outcome is: 28
am i right?