The First Class Function
A medium Python interview practice problem on DataDriven. Write and execute real python code with instant grading.
- Domain
- Python
- Difficulty
- medium
- Seniority
- L4
Problem
Implement `first_class_demo(test_cases)`, where `test_cases` is a list of dicts. Each dict has an `op` of either `'apply_twice'` or `'compose'` and an integer `x`. Inside, build a registry of named one-argument functions: `'double'` = x*2, `'inc'` = x+1, `'square'` = x*x. For an `'apply_twice'` op, look up the named function in `f` and return `f(f(x))`. For a `'compose'` op, look up `f` and `g`, build the composed function `lambda x: f(g(x))` (apply `g` first, then `f`), and apply it to `x`. Return the list of results, one per test case, in the same order as the input. Your implementation should pass functions as values and return a function from `compose` (closure). An empty `test_cases` returns an empty list.
Summary
Functions travel as values - prove you can pass one around.
Practice This Problem
Solve this Python problem with real code execution. DataDriven runs your Python code in a real environment and grades it automatically.