ProgrammingHardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
from functools import lru_cache
grid = [[1, 3, 1], [1, 5, 1], [4, 2, 1]]
@lru_cache(maxsize=None)
def best(r, c):
    if r == 0 and c == 0:
        return grid[0][0]
    opts = []
    if r > 0:
        opts.append(best(r - 1, c))
    if c > 0:
        opts.append(best(r, c - 1))
    return grid[r][c] + min(opts)
print(best(2, 2), best.cache_info().misses)
  1. A. 7 8
  2. B. 7 9
  3. C. 9 9
  4. D. 7 7

Correct answer: B. 7 9

The cheapest path to (2, 2) costs 7, and the cache misses once for each of the nine cells, since each cell is computed once.

More Python Programming questions

Exams that ask this topic