← 返回 databricks 的题目列表Design and Implement a Lazy Array with Testable Laziness
类型:online_judge
Problem: Implement a Lazy Array and Explain How to Test Its Laziness
Implement a lazily-evaluated array/sequence LazyArray.
Requirements
LazyArray should be defined by a generator/computation function for element values, instead of computing all elements eagerly.
An element is computed only when it is accessed (e.g., by index) or when a materialization is triggered.
Decide whether to cache computed elements (if not specified, explain your choice and implement accordingly).
Interface (you may adjust as long as it is consistent)
__len__(): return the length.
get(i) / __getitem__(i): return the i-th element.
materialize(): return a normal Python list (or equivalent), computing all elements.
Discussion
How would you test that the implementation is truly lazy? Provide actionable testing ideas (e.g., using a side-effectful function to verify “not computed until accessed”, and to verify caching behavior).
Constraints
n up to 1e5.
Access should be as close to amortized O(1) as possible (if cached).
Example (illustrative)
Input: n=5, f(i)=i*i
Operation: get(3)
Output: 9
Example
Input
n=5, f(i)=i*i; ops: get(3)
Output
9