ProgrammingVery hardGATE CS · Product-company placement

What is printed?

What is printed?
def f(n):
    if n == 0:
        return []
    return [n] + f(n - 1) if n % 2 else f(n - 1) + [n]
print(f(5))
  1. A. [5, 3, 1, 2, 4]
  2. B. [5, 4, 3, 2, 1]
  3. C. [1, 2, 3, 4, 5]
  4. D. [4, 2, 1, 3, 5]

Correct answer: A. [5, 3, 1, 2, 4]

Odd n is prepended and even n appended around f(n-1): f(1) = [1], f(2) = [1, 2], f(3) = [3, 1, 2], f(4) = [3, 1, 2, 4], f(5) = [5, 3, 1, 2, 4].

More Python Programming questions

Exams that ask this topic