I have a list x
of number values.
To begin, I specify a range. I want to grab values from x
that lie within this range. The range of values would be ±R
from the median of x
. I want to adjust R
to obtain a specific amount of values N
. The only way I can see of achieving this is through some kind of feedback loop. What would be a quick and efficient way of getting closest to N
as possible?
eg.
x = ['3','5','1','2','4']
I want the range of values from 3-R<3<3+R
as 3
is the median. Let's say N = 3
. The obtained values would be ['2','3','4']
with R
worked as as 1.
EXAMPLE CODE:
N = 3
x = ['3','5','1','2','4']
R = 1
n = some number to allow room for error
y = values of x in range ±R from median
while len(y) > N+n or len(y) < N-n:
if len(y) > N+n:
R -= ADJUST VALUE PROPORTIONAL TO ERROR HERE?
if len(y) < N-n:
R += ADJUST VALUE PROPORTIONAL TO ERROR HERE?
y = values of x in range ±R from median (update y list with new R)