Last active
October 20, 2015 23:03
-
-
Save davehughes/2489a6d7866f8d0e8301 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import itertools | |
| DIMENSIONS = { | |
| 'city': [ | |
| 'sf', 'nyc', 'la', 'chicago', | |
| ], | |
| 'color': [ | |
| 'red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet', | |
| ], | |
| 'car_make': [ | |
| 'porsche', 'audi', 'bmw', 'tesla', | |
| ], | |
| } | |
| def to_list(x): | |
| return x if type(x) == list else [x] | |
| def project_combinations(spec): | |
| resolved = {} | |
| for k, v in spec.iteritems(): | |
| resolved_vals = [] | |
| for o in to_list(v): | |
| if type(o) == dict: | |
| resolved_vals.extend(to_list(project_combinations(o))) | |
| else: | |
| resolved_vals.append(o) | |
| resolved[k] = resolved_vals | |
| return expand_combinations_dict(resolved) | |
| def expand_combinations_dict(o): | |
| ''' | |
| Given a dict whose keys map to one or more values, return a list of dicts | |
| representing all combinations of those values: | |
| Example: | |
| input = { | |
| 'first_name': ['Alice', 'Bob', 'Clyde'], | |
| 'last_name': 'Smith', | |
| } | |
| expand_combinations_dict(input) | |
| => [ | |
| {'first_name': 'Alice', 'last_name': 'Smith'}, | |
| {'first_name': 'Bob', 'last_name': 'Smith'}, | |
| {'first_name': 'Clyde', 'last_name': 'Smith'}, | |
| ] | |
| ''' | |
| combo_tuples = [] | |
| for k, v in o.iteritems(): | |
| key_tuples = list(itertools.product([k], to_list(v))) | |
| combo_tuples.append(key_tuples) | |
| combinations = itertools.product(*combo_tuples) | |
| return [dict(c) for c in combinations]' | |
| if __name__ == '__main__': | |
| print project_combinations(DIMENSIONS) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice.