ProgrammingHardGATE CS · Product-company placement

What is printed?

What is printed?
cache = {}
def ways(n):
    if n < 0: return 0
    if n == 0: return 1
    if n not in cache:
        cache[n] = ways(n - 1) + ways(n - 2) + ways(n - 3)
    return cache[n]
print(ways(5), len(cache))
  1. A. 13 5
  2. B. 8 5
  3. C. 13 6
  4. D. 24 5

Correct answer: A. 13 5

ways(n) counts step sequences of 1, 2 or 3 (tribonacci): 1, 1, 2, 4, 7, 13 for n = 0..5. The cache stores n = 1..5 (n = 0 and negatives return early), so 5 entries.

More Python Programming questions

Exams that ask this topic