1

I am attempting to understand exactly how this function works, I have been playing around with it but I am unsure.

  • What I know: anything with a remainder of 1 (odd number) will return 0

  • What I am confused about: When I calculate it I got 2 which would result in but isn't '36//2 + 1' equal to '19' and not '2'?

Code:

def anon(n):
    if n % 2 == 1:
        return 0
    else:
        return 1 + anon(n//2)

print(anon(36))
4
  • 3
    Because it's calculating 1 + anon(18), not just 1 + 18. The keyword you seem to be missing is "recursive". Commented Jun 14, 2016 at 13:11
  • 1
    anon(36)>1+anon(18)>1+(1+anon(9))>1+1+0=2 Commented Jun 14, 2016 at 13:14
  • Suggest also to either use a debugger or try to step through code flow with tools like pythontutor dot com in case you want to find out yourself, I have prepared a permanent link: pythontutor.com/… Commented Jun 14, 2016 at 13:16
  • Checking it out now :) Commented Jun 14, 2016 at 13:27

4 Answers 4

3

Let's see what happens with anon(36):

36 % 2 is not == to 1, so it returns 1 + anon(18).

18 % 2 is not == to 1, so it returns 1 + anon(9).

9 % 2 is == 1, so it returns 0.

Add up all the returns to get: 1 + 1 + 0 = 2. I suggest looking into how recursion works with stack diagrams! Note that you're calling your anon() function again, which is why it keeps going.

Sign up to request clarification or add additional context in comments.

Comments

2

nope that's not true since anon(36/2) will itself call anon recursively and NOT just return 19

Comments

1

The function tells you, how often you can divide a number by two, as it calls itself recursively with the half of the original in input (if the input is even). It effectively counts who often it calls itself until returning 0, by adding 1 to its return value with each recursive call.

Comments

1

If you trace the function calls, this is what you are getting:

anon(36) # First call, even number = 1
1 + anon(36//2 = 18) # Even number = 1
1 + 1 + anon(18//2 = 9) # Odd number = 0
1 + 1 + 0 = 2 # Returned value

Hence, the return value is 2.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.