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

Python divide list into percentages

I have a function that applies random colors to each set of elements defined by a percentage. In this case I have a list of 154 elements to start with, but somehow in the end I get only 152 processed elements. Not sure why, because I am giving it 100% in total when I call the function at the end.

import maya.cmds as cmds
import random

def selector(percents):
    RandomSelection = []
    mySel = cmds.ls(sl=1) # a list of elements with a total of 154
    random.shuffle(mySel)
    
    start = 0
    for cur in percents:
        end = start + cur * len(mySel) // 100
        RandomSelection.append(mySel[start:end])
        start = end
    
    print(len(mySel)) # 154
    print ( sum( [ len(listElem) for listElem in RandomSelection]) ) # 152 # why not 154?
    
    for mesh in RandomSelection:
        r = [random.random() for i in range(3)]
        cmds.polyColorPerVertex(mesh,rgb=(r[0], r[1], r[2]), cdo=1 )
    

selector([70, 10, 15, 5])
#154
#152

Thank you.

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

>Solution :

end = start + cur * len(mySel) // 100 can drop up to 1 element at each iteration due to flooring.

Try this instead :

start = 0
cumul = 0
for cur in percents:
    cumul += cur
    end = cumul * len(mySel) // 100
    RandomSelection.append(mySel[start:end])
    start = end

This will still drop up to 1 at every iteration due to florring, but these drops won’t accumulate (since you recompute your end from fresh), and at the end you are guaranteed to have an exact division, and so use up all elements.

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