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

How to create a random list that satisfy a condition (in one try)?

I have written the following code to generate a random list. I want the list to have elements between 0 and 500, but the summation of all elements does not exceed 1300. I dont know how to continue my code to do that. I have written other codes; for example, to create a list of random vectors and then pick among those that satisfy the condition. But here I want to create such a list in one try.

nv = 5
bounds = [(0, 500), (0, 500), (0, 500), (0, 500), (0, 500)]
var =[]
for j in range(nv):
    var.append(random.uniform(bounds[j][0], bounds[j][1]))
    summ = sum(var)
    if summ > 1300:
        ????

>Solution :

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

Don’t append until after you’ve validated the value.

Use while len() < maxLen so that you can handle repeat attempts.

You don’t really need nv since len(bounds) dictates the final value of len(var).

len(var) is also the next index of the var list that is unused so you can use that keep track of where you are in bounds.

import random

bounds = [(0, 500), (0, 500), (0, 500), (0, 500), (0, 500)]
var = []
runningSum = 0
while len(var) < len(bounds):
    sample = random.uniform(bounds[len(var)][0], bounds[len(var)][1])
    if runningSum + sample < 1300:
        runningSum += sample
        var.append(sample)
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