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 :
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)