Consider the following Python code snippet.
def f(a,b):
if (a==0):
return b
if (a%2==1):
return 2*f((a-1)/2,b)
return b+f(a-1,b)
print(f(15,10))The value printed by the code snippet is ____________ (Answer in integer)
Consider the following Python code snippet.
def f(a,b):
if (a==0):
return b
if (a%2==1):
return 2*f((a-1)/2,b)
return b+f(a-1,b)
print(f(15,10))The value printed by the code snippet is ____________ (Answer in integer)
ANSWER
The value printed is 160 (Python 3 shows it as 160.0, which is the integer 160).
Official answer: 160Source: Official answer key, GATE 2025 DA (IIT Roorkee)
Start with f(15,10). Here a = 15, so a==0 is false. Also 15 % 2 == 1 is true, so the second if fires and the call returns 2*f((15-1)/2, 10). In Python 3, / is true division, so (15-1)/2 is the float 7.0. The first argument is a float from here on, but this changes no branch: 7.0 == 0 is false, 7.0 % 2 is 1.0, and 1.0 == 1 is true.
f(7.0,10): not zero and odd, so it returns 2*f(3.0,10), since (7.0-1)/2 = 3.0.
f(3.0,10): not zero and odd, so it returns 2*f(1.0,10), since (3.0-1)/2 = 1.0.
f(1.0,10): not zero and odd, so it returns 2*f(0.0,10), since (1.0-1)/2 = 0.0.
f(0.0,10): 0.0 == 0 is true in Python, so the first if fires and it returns b = 10.
Every argument on the way down (15, 7.0, 3.0, 1.0) was odd, so the last line return b+f(a-1,b) is never reached. Only the doubling branch is used, and it is used exactly four times.
Unwind: , , , . The program prints 160.0, since the result of 2*f(7.0,10) is a float. The integer answer is , which equals .
KEY IDEA
Trace the recursion and watch the parity of the first argument. 15, 7, 3 and 1 are all odd, so each call just doubles the result of the next, down to the base case f(0,b) = b. The answer is , where is the number of halvings from 15 to 0. Python 3's / makes the arguments floats, but 7.0 % 2 == 1 and 0.0 == 0 still behave as for integers.
WATCH OUT FOR
Taking the final line b+f(a-1,b) as if it runs at every level, which gives a sum instead of a product. Another slip is to worry that the float arguments (7.0, and so on) break the a%2==1 or a==0 tests. They do not, because float values compare equal to the matching integers.
From the GATE 2025 DA paper. Every question of this paper · Download the full paper · All 10 Python questions, with notes