Last active
December 15, 2015 12:19
-
-
Save jmcarp/5259520 to your computer and use it in GitHub Desktop.
states_to_colors
This file contains 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
def states_to_colors(states, cols): | |
'''Generate all possible mappings of states to colors. | |
Args: | |
states (list) : list of state names | |
cols (list) : list of color names | |
Returns: | |
list of dictionaries of state-color mappings | |
Example use: | |
>>> states_to_colors(['NY', 'MO'], ['r', 'g']) | |
[{'NY': 'r', 'MO': 'r'}, {'NY': 'r', 'MO': 'g'}, {'NY': 'g', 'MO': 'r'}, {'NY': 'g', 'MO': 'g'}] | |
''' | |
# Start with mappings for one state | |
mappings = [{states[0] : col} for col in cols] | |
# Add mappings for states > 1: | |
# For each state, add all possible colors to all | |
# existing mappings. | |
for state in states[1:]: | |
_mappings = [] | |
for mapping in mappings: | |
for c in cols: | |
_mappings.append(dict(mapping, **{state:c})) | |
mappings = _mappings | |
# Done | |
return mappings |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment