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.

4 Comments

You can help us by Clicking on ads. ^_^
Please do not send spam comment : )

  1. Pls check , it should return 4 not True

    ReplyDelete
    Replies
    1. No, we are calling chek() function recursively.

      Delete
  2. can you please say the working process

    ReplyDelete
    Replies
    1. 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.

      Delete

Post a Comment

You can help us by Clicking on ads. ^_^
Please do not send spam comment : )

Previous Post Next Post