HardPro challengePython
Observable (map / filter / take)
PythonDesignReactive
Implement a minimal synchronous Observable class:
Observable.of(*values)— static factory from a sequence of values.obs.map(fn)— returns a new Observable applyingfnto each value.obs.filter(fn)— returns a new Observable keeping values wherefnis truthy.obs.take(n)— returns a new Observable with at mostnvalues.obs.subscribe({'next': fn})— runs the chain synchronously, callingfnfor each value.
solve applies a declarative operator chain to a list of values.
Operators: ['map', expr], ['filter', expr], ['take', n] whereexpr is a lambda string compiled with eval.
Sample tests
Test #1map doubles values
Input: [[["map","lambda x: x * 2"]],[1,2,3,4]]
Output: [2,4,6,8]
Test #2filter keeps even numbers
Input: [[["filter","lambda x: x % 2 == 0"]],[1,2,3,4,5,6]]
Output: [2,4,6]
Test #3take limits the output
Input: [[["take",3]],[10,20,30,40,50]]
Output: [10,20,30]
Test #4Chained map+filter+take
Input: [[["map","lambda x: x * 2"],["filter","lambda x: x > 4"],["take",2]],[1,2,3,4,5]]
Output: [6,8]
Test #5No operators passes through unchanged
Input: [[],[1,2,3]]
Output: [1,2,3]