Recursive Function | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Recursive Function

Can someone please describe this recursive function: def power(x, y): if y == 0: return 1 else: return x * power(x, y-1) print(power(2, 3)) Thank you

19th May 2020, 6:02 AM
Mojtaba Moghaddam
Mojtaba Moghaddam - avatar
3 Answers
+ 1
This function do exponentials Like power(2,3)=8 When call it in the first time assume that y=3 and x=2 y==0 #false Goto else 2*power(2,2) Goto second call y==0 #false Goto else 2*power(2,1) Goto third call y==0 #true Return 1 Which means 2*power(2,2) And that's equal to 2*(2*power(2,1)) #the value of power(2,2) And that's equal to 2*(2*(2*power(2,0))) #the value of power(2,1) And the value of power(2,0) is 1 And that's is... According to the previous calculations 2*2*2*1 which equal to 8
19th May 2020, 6:17 AM
ycsvenom
ycsvenom - avatar
+ 1
Whenever the function gets called i.e., power(2,3) [here] control goes to function... Enters into the function and starts executinh the stmts we have written... There you given two conditions... If y==0, this got failed and control now goes to else part.. There you have given return x*power(x, y-1) which is a recursive function... Until the y value equals to zero, it will get executed repeatedly... Simply, First time: x*power(x, y-1) = 2*power(2,2) second time: now, y value equals to 2 So, 2*2*power(2,1) Third time: now, y value equals to 1 So, 2*2*2*power(2,0) Fourth time : y value became 0 So,if Condiction is true and returns 1 so, y became 1 So,finally 2*2*2*2 which is equal to 8
19th May 2020, 6:17 AM
sarada lakshmi
sarada lakshmi - avatar
+ 1
2 * power(2, 2) 2 * power(2, 1) 2 * 1 2*2*2*1 = 8
19th May 2020, 8:17 AM
Ahmed Muhammed
Ahmed Muhammed - avatar