Randomnly select numbers from a list with a condition

Question:

I have a list(range(30000)). I need to randomnly select numbers inside it such that, it takes a certain count of numbers say 'n' in total at the same time it should take 'k' number of values between two index positions.

For example:

a = [1,2,3,4,5,,6,7,8......20,21,22......88,89.....30k]

I need to select 5000 numbers in total. 'x' numbers between 0th index to 100th index, 'y' numbers between 100 to 200 etc.

There is no hard rule that it should select 5000 numbers itself. But it should sure lie between 0-100, 100-200 etc.

I saw random.choice but how to give it a condition

To put the question accurately: I need 50 numbers from 0-100,200-300 etc.

Asked By: Fasty

||

Answers:

Here’s one way to approach this:

import random
# define the sample size of each interval
# or for your specific case generate a sequence
# that adds up to 5000
size = [5, 2, 10]
n = 300
step = 100

# iterate over both a range (or sequence) and size
# and take random samples accordingly
out = [random.sample(list(range(i-step,i)), k) 
               for i, k in zip(range(step, n+step, step), size)]

print(out)
[[6, 86, 96, 62, 53], [115, 176], [245, 259, 297, 249, 225, 281, 264, 274, 275, 206]]
Answered By: yatu

This is a simple script that does exactly what you asked for.

import random
a = 0
b=100
l = list()
for z in range(149):
    a = a+200
    b = b+200
    for x in range(50):
        l.append(random.randint(a,b))
Answered By: Tommy Lawrence
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.