Specific instance of Problem
I have an int range from 1-100. I want to generate n total numbers within this range that are as evenly distributed as possible and include the first and last values.
Example
start = 1, end = 100, n = 5
Output: [1, 25, 50, 75, 100]
start = 1, end = 100, n = 4
Output: [1, 33, 66, 100]
start = 1, end = 100, n = 2
Output: [1, 100]
What I currently have
I actually have a working approach but I keep feeling I am over thinking this and missing something more simple? Is this the most efficient approach or could this be improved?
def steps(start, end, n):
n = min(end, max(n, 2) - 1)
mult = end / float(n)
yield start
for scale in xrange(1, n+1):
val = int(mult * scale)
if val != start:
yield val
Note, I am ensuring that this function will always return at least the lower and upper limit values of the range. So, I force n >= 2
Just for search reference, I am using this to sample image frames from a rendered sequence, where you would usually want the first, middle, last. But I wanted to be able to scale a bit better to handle really long image sequences and get better coverage.
Solved: From the selected answer
I ended up using this slightly modified version of @vartec's answer, to be a generator, and also cap the n
value for safety:
def steps(start,end,n):
n = min(end, max(n, 2))
step = (end-start)/float(n-1)
return (int(round(start+x*step)) for x in xrange(n))
You need proper rounding:
def steps(start,end,n):
if n<2:
raise Exception("behaviour not defined for n<2")
step = (end-start)/float(n-1)
return [int(round(start+x*step)) for x in range(n)]
Extra dependency and maybe overkill, but short, tested and should give correct results: numpy.linspace
>>> numpy.linspace(1, 100, 4).astype(int).tolist()
[1, 34, 67, 100]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With