Bird
0
0

Which code snippet correctly implements caching to avoid redundant computations?

easy📝 Syntax Q3 of 15
Agentic AI - Production Agent Architecture

Which code snippet correctly implements caching to avoid redundant computations?

cache = {}
def calculate(n):
    # What should be done here?
Aresult = n + 5 return result
Bif n in cache: return cache[n] result = n + 5 cache[n] = result return result
Ccache[n] = n + 5 return cache[n]
Dif n not in cache: return n + 5 else: return cache[n]
Step-by-Step Solution
Solution:
  1. Step 1: Check cache existence

    Verify if the input 'n' is already in the cache to reuse the stored result.
  2. Step 2: Compute and store if missing

    If not cached, compute the result and save it in the cache for future calls.
  3. Final Answer:

    if n in cache: return cache[n] result = n + 5 cache[n] = result return result correctly implements this logic.
  4. Quick Check:

    Cache lookup before compute ensures efficiency. [OK]
Quick Trick: Always check cache before computing to save time [OK]
Common Mistakes:
  • Not storing the computed result in cache
  • Computing result without checking cache first
  • Returning result without caching it
  • Incorrect cache key usage

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Agentic AI Quizzes