Q. Consider following Python function that uses recursion:
def check(n):
if n <= 1:
return True
elif n % 2 == 0 :
return check(n/2)
else:
return check(n/1)
What is the value returned by check(8)?
Answer :
Value returned by check(8) is ‘True’.
Explaination :
When check(8) is called, the value of "n" is 8. Since 8 is divisible by 2, the function enters the elif condition and makes a recursive call to check(8/2), which is check(4).
Again, check(4) is called. Since 4 is also divisible by 2, another recursive call is made to check(4/2), which is check(2).
Once more, check(2) is called. Since 2 is divisible by 2, another recursive call is made to check(2/2), which is check(1).
Finally, check(1) is called. Here, the base case is met because 1 is less than or equal to 1. Hence, True is returned.
Therefore, the value returned by check(8) is True.
Pls check , it should return 4 not True
ReplyDeleteNo, we are calling chek() function recursively.
Deletecan you please say the working process
ReplyDeleteWhen check(8) is called, the value of "n" is 8. Since 8 is divisible by 2, the function enters the elif condition and makes a recursive call to check(8/2), which is check(4).
DeleteAgain, check(4) is called. Since 4 is also divisible by 2, another recursive call is made to check(4/2), which is check(2).
Once more, check(2) is called. Since 2 is divisible by 2, another recursive call is made to check(2/2), which is check(1).
Finally, check(1) is called. Here, the base case is met because 1 is less than or equal to 1. Hence, True is returned.
Therefore, the value returned by check(8) is True.
Post a Comment
You can help us by Clicking on ads. ^_^
Please do not send spam comment : )