Generate Cartesian Product of Search Space Parameters
Arrays & HashingAuto-graded · 20 test casesLast updated
Construct all explicit configurations from a dictionary mapping parameter names to lists of candidate values using Cartesian product generation.
Given a dictionary grid where each key is a parameter name and its corresponding value is a list of candidate settings for that parameter, construct and return a list of dictionary configurations representing every possible parameter combination.
Each returned dictionary should map every key from grid to a single value selected from its list of candidates. The sequence of candidate choices should follow Cartesian product ordering, where values belonging to the rightmost keys vary the fastest (matching the order of nested iteration across the dictionary's keys in insertion order).
Special Rules
- If
gridis empty ({}), return a list containing a single empty dictionary:[{}]. - If any key maps to an empty list (
[]), no valid combination can be formed, so return an empty list ([]). - The order of keys in each configuration dictionary must match the insertion order of keys in the input dictionary.
- Duplicate entries within candidate lists should be preserved as separate distinct configurations.
Constraints
- The number of keys in
gridis between0and10. - Each candidate list contains between
0and10elements. - Parameter names are non-empty strings.
- Values can be of any data type (e.g., integers, floats, strings, standard Python objects).
Examples
Example 1
Input: generate_hyperparameter_combinations({'learning_rate': [0.1, 0.2], 'feature': ['A', 'B'], 'batch': [10, 20]})
Output: [{'learning_rate': 0.1, 'feature': 'A', 'batch': 10}, {'learning_rate': 0.1, 'feature': 'A', 'batch': 20}, {'learning_rate': 0.1, 'feature': 'B', 'batch': 10}, {'learning_rate': 0.1, 'feature': 'B', 'batch': 20}, {'learning_rate': 0.2, 'feature': 'A', 'batch': 10}, {'learning_rate': 0.2, 'feature': 'A', 'batch': 20}, {'learning_rate': 0.2, 'feature': 'B', 'batch': 10}, {'learning_rate': 0.2, 'feature': 'B', 'batch': 20}]
Example 2
Input: generate_hyperparameter_combinations({'optimizer': ['sgd', 'adam'], 'epochs': [10, 50]})
Output: [{'optimizer': 'sgd', 'epochs': 10}, {'optimizer': 'sgd', 'epochs': 50}, {'optimizer': 'adam', 'epochs': 10}, {'optimizer': 'adam', 'epochs': 50}]
Example 3
Input: generate_hyperparameter_combinations({'seed': [1]})
Output: [{'seed': 1}]
Example 4
Input: generate_hyperparameter_combinations({})
Output: [{}]
Hints
Hint 1
Think of this task as computing a Cartesian product over the sequences of candidate values associated with each parameter key.
Hint 2
The `itertools.product` module in Python provides a convenient standard library tool to generate Cartesian combinations in lexicographical order.
Hint 3
Combine key names with each generated tuple of values using `zip(keys, values)` to form individual candidate dictionaries.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
To generate every possible configuration in the given search space, we need to take the Cartesian product of all candidate lists associated with the input dictionary keys:
- Extract the sequence of keys from
gridin their original order. - Extract the list of candidate values corresponding to each key.
- Use Python's built-in
itertools.productfunction, passing all candidate value lists as unpacked positional arguments.itertools.productgenerates tuples where elements from the last sequence vary fastest, which matches standard nested loop behavior. - For each produced value tuple, pair it with the parameter keys using
zip(keys, values)and build a dictionary configuration. - Materialize all configuration dictionaries into a list.
Correctness & Edge Cases
- Empty Grid (
{}): Unpacking zero candidate lists intoproduct()yields a single empty tuple(). Pairingzip(keys, ())produces an empty dictionary{}, resulting in[{}]. - Empty Candidate List (
[]): If any key maps to an empty candidate list,product(*value_lists)produces no tuples, yielding an empty result[]. - Preserving Duplicates:
itertools.producttreats positional indices as distinct, ensuring that duplicate candidate values in a list are preserved properly in the output without implicit deduplication.
Complexity
Let $K$ be the number of keys in the dictionary and $N$ be the total number of valid parameter combinations (i.e., the product of lengths of all value lists, $N = \prod |V_i|$).
- Time Complexity: $\mathcal{O}(N \cdot K)$. Generating each combination dictionary requires inserting $K$ key-value pairs. Since output size dominates, this time complexity is optimal.
- Space Complexity: $\mathcal{O}(N \cdot K)$ auxiliary space to store and return the list of generated dictionaries.
Python Reference Code
from itertools import product
from typing import Dict, List, Any
def generate_hyperparameter_combinations(grid: Dict[str, List[Any]]) -> List[Dict[str, Any]]:
keys = list(grid.keys())
value_lists = [grid[k] for k in keys]
return [dict(zip(keys, values)) for values in product(*value_lists)]