Last active
June 30, 2026 13:57
-
-
Save sumancbd/738528d0402d7d71db5959175e65c0d1 to your computer and use it in GitHub Desktop.
Python Interview Question: Memoize Function Using Closure (supports multiple args + mutable inputs like lists/dicts)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| Python Coding Question: Memoize Function Using Closure | |
| ====================================================== | |
| You are given a function. Write another function called `memoize` that can wrap | |
| any function and cache its result. | |
| If the wrapped function is called again with the same input, it should return | |
| the cached result instead of executing the original function again. | |
| The input can be of any type: integer, string, tuple, list, dictionary, or | |
| multiple arguments. | |
| Requirements | |
| ------------ | |
| Implement `memoize(fn)` such that: | |
| 1. It accepts any function as input. | |
| 2. It returns a new function. | |
| 3. The new function should cache previous results. | |
| 4. If the same arguments are passed again, return the cached value. | |
| 5. It should support multiple arguments. | |
| 6. It should handle mutable inputs like lists and dictionaries if possible. | |
| """ | |
| def memoize(fn): | |
| # write your code here | |
| pass | |
| # Example 1 | |
| def add(a, b): | |
| print("calculating...") | |
| return a + b | |
| memoized_add = memoize(add) | |
| print(memoized_add(2, 3)) # calculating... 5 | |
| print(memoized_add(2, 3)) # 5, should come from cache | |
| print(memoized_add(4, 5)) # calculating... 9 | |
| # Example 2 | |
| def greet(user): | |
| print("generating greeting...") | |
| return f"Hello {user['name']}" | |
| memoized_greet = memoize(greet) | |
| print(memoized_greet({"name": "Suman"})) | |
| print(memoized_greet({"name": "Suman"})) | |
| # should ideally return cached result if input value is same | |
| # Expected Output Behavior | |
| # ------------------------ | |
| # calculating... | |
| # 5 | |
| # 5 | |
| # calculating... | |
| # 9 | |
| # generating greeting... | |
| # Hello Suman | |
| # Hello Suman |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment