The Op Dispatcher
An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- easy
- Seniority
- L4
Problem
Records in a pipeline's transform step carry a value that is either a number or text, and op_name is always one of double, square, abs, upper or lower. Return every record in records with its existing fields plus a result holding the transformed value.
Name the operation, apply it everywhere.
Example 1
Input:
records = [{"id":1,"value":5},{"id":2,"value":3}], op_name = "double"Output:
[{"id":1,"value":5,"result":10},{"id":2,"value":3,"result":6}]Example 2
Input:
records = [{"id":1,"value":"hello"}], op_name = "upper"Output:
[{"id":1,"value":"hello","result":"HELLO"}]Worked solution and explanation
This is a lookup table dressed up as an ETL step. The skill being probed: can you turn an operation name into the right transform and apply it to every record, including the names the examples never show? The examples only exercise double and upper, and that is the trap. The candidate who writes two branches plus a passthrough passes both, then returns 4 for square of 4 and leaves 'WORLD' untouched under lower. The statement names five operations, and the graded cases use all five.
Build the table, then apply it
Step 1: Name every operation once
Put all five operations from the statement in one dict keyed by name: double, square, abs, upper, lower. The examples are a sample of the contract, not the contract. The table is where you show you read the whole statement.
Step 2: Resolve the operation before the loop
Look up ops[op_name] once. The operation is the same for every record, so resolving it per record is wasted work. A bad name also fails fast with a KeyError instead of halfway through the batch.
Step 3: Copy the record, then add result
dict(record) gives a fresh record that keeps id, value and anything else upstream attached. Only the copy gets result, and records come back in the order they arrived.
def apply_transform(records, op_name):
ops = {
'double': lambda x: x * 2,
'square': lambda x: x ** 2,
'abs': lambda x: abs(x),
'upper': lambda x: str(x).upper(),
'lower': lambda x: str(x).lower(),
}
transform = ops[op_name]
transformed = []
for record in records:
new_record = dict(record)
new_record['result'] = transform(record['value'])
transformed.append(new_record)
return transformedCommon follow-up questions
- What if the operation name is not in the dispatch map? (Tests raising a clear error versus returning a default.)
- How would you support user-defined operations? (Tests accepting callables as parameters or a registry pattern.)
- What if operations could chain, for example `double` then `square`? (Tests function composition or pipeline patterns.)