Created
March 15, 2016 21:16
-
-
Save nichochar/52f15e151ede5dfec31c 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
| class InvalidInput(Exception): | |
| pass | |
| def possible_combinations(attributes): | |
| """Takes in a user_attribute like described above, and returns | |
| all possible combinations of 1 of each of the attributes | |
| Every attribute has a list | |
| Returns: | |
| ======= | |
| prints out all the uniques, one by line | |
| """ | |
| keys = attributes.keys() | |
| results = [] | |
| for key in keys: | |
| if not isinstance(attributes[key], list): | |
| raise InvalidInput | |
| def recursive_down(current_values, attributes, results): | |
| """ | |
| current_keys: list of previously selected keys to keep until we reach the bottom | |
| attributes: what is left of the attributes dict (gets smaller every iteration) | |
| results: the global results we're saving | |
| """ | |
| if len(attributes.keys()) == 0: | |
| results.append(current_values) | |
| return | |
| new_key = attributes.keys()[0] | |
| temp_attributes = attributes.copy() | |
| del temp_attributes[new_key] | |
| for elt in attributes[new_key]: | |
| recursive_down(current_values + [elt], temp_attributes, results) | |
| return | |
| recursive_down([], attributes, results) | |
| return results | |
| user_attribute = { | |
| 'Country': ['US', 'CA', 'CH', 'JP'], | |
| 'AgeRange': ['0-20', '21-30', '31-40'], | |
| 'Gender': ['M', 'F'], | |
| 'Income': ['L', 'M', 'H'], | |
| 'MusicPref': ['Jazz', 'Pop'], | |
| } | |
| combinations = possible_combinations(user_attribute) | |
| for combination in combinations: | |
| print combination |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment