Lazy Array
DatabricksOnsiteMedium
Build LazyArray, a list of integers that records transformations and applies them only when a value is needed.
The constructor takes the starting values. An array is named by an integer handle: the starting array is handle 0, and every call to map creates a new array with the next handle (1, 2, ...) without changing any existing one.
A transformation is a string: "add:k", "sub:k" and "mul:k" apply + k, - k and * k to an element, and "neg" negates it. Each application of one transformation to one element is a call, and calls() returns how many calls have been made so far.
Each test drives one LazyArray(values) instance through a sequence of calls and checks every return value.
Part 1: Deferred map and search
Implement a lazy integer array. The constructor takes the starting values; that array has handle 0.
map(handle, op)returns the handle of a new array whose elements are those of arrayhandlewithopapplied. It must not applyopto anything yet. New handles are1,2, ... in creation order.index_of(handle, target)returns the smallest index whose element in arrayhandleequalstarget, or-1if there is none. Elements are produced one at a time from index0, each by applying the whole chain of transformations from the starting array, and the search stops at the first match.calls()returns the number of single transformation applications made so far.
A transformation is one of "add:k", "sub:k", "mul:k" (apply + k, - k, * k) or "neg" (negate the element).
- Example 1
- init
[[4,7,2,7,9]]- operations
[["map",[0,"add:3"]],["map",[1,"mul:2"]],["calls",[]],["index_of",[2,20]],["calls",[]],["index_of",[0,7]],["calls",[]],["index_of",[2,99]],["calls",[]],["index_of",[1,5]],["calls",[]]]- Output
[1,2,0,1,4,1,4,-1,14,2,17]
Why:
maponly records operations, socalls()stays 0 after two maps. Array 2 is [4,7,2,7,9] plus 3, times 2, which is [14,20,10,10,24].index_of(2, 20)looks at index 0 (2 calls, value 14) and index 1 (2 calls, value 20) and stops: 4 calls.index_of(0, 7)checks index 0 (4, no) and index 1 (7, yes) on the untouched original, with no calls.index_of(2, 99)evaluates all five elements with 2 calls each, 10 more calls, and finds nothing. Array 1 is [7,10,5,10,12], soindex_of(1, 5)stops at index 2 after 3 elements, 3 calls.
Constraints
1 <= len(values) <= 10^3-10^9 <= values[i] <= 10^9-10^3 <= k <= 10^3inadd:k,sub:kandmul:k1 <= len(operations) <= 10^4handlewas returned by an earlier call tomap, or is0