Tylv
Tylv

Reputation: 39

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.

Code:

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

print(anon(36))

Upvotes: 1

Views: 140

Answers (4)

Božo Stojković
Božo Stojković

Reputation: 2943

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.

Upvotes: 1

Tim
Tim

Reputation: 106

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.

Upvotes: 3

Leon
Leon

Reputation: 3036

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.

Upvotes: 1

DomTomCat
DomTomCat

Reputation: 8569

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

Upvotes: 2

Related Questions