Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating a list of colors based upon a partition of the set {0,1,..,n-1}

I have a partition of the set {0,1,…,n-1} into a list of m subsets along corresponding to m colors. I need to assign each index in my set to the corresponding color.

As a simple example, if n=8 and m=3, let

partition=[{0,2},{1,4,6},{3,5,7}]
colors=['r','b','c']

I want to create the list ['r','b','r','c','b','c','b','c']

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What is the most "pythonic" way of doing this, preferably without loops?

>Solution :

One way is to create a mapping from partition to colors, sort it; then get the values:

d = {k:v for s, v in zip(partition, colors) for k in s}
out = [d[k] for k in sorted(d)]

Output:

['r', 'b', 'r', 'c', 'b', 'c', 'b', 'c']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading