TAGS :Viewed: 24 - Published at: a few seconds ago

[ Python Basic Math Algorithm Function ]

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))

Answer 1


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.

Answer 2


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

Answer 3


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.

Answer 4


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.