2

I'm trying to implement a piece of code with Python3 that generates a list of n equally spaced numbers (which may be rational) that range between two specified numbers.

For example: if n = 3, x = -1 and y = 1, the result should be [-1,0,1].

My assumption is that this should use numpy's arange with the step calculated from these three values, but I can't figure out the math. In this simple example, the step would be = 1, but if x = 0 and y = 1, the step is .5.

Alexandre B.
  • 5,387
  • 2
  • 17
  • 40
theupandup
  • 335
  • 3
  • 14

3 Answers3

4

You can do it without numpy using a simple generator:

def numbers(x, y, n):
    assert n > 1
    step = (y - x) / (n - 1)
    for i in range(n):
        yield x + i*step

print(list(numbers(-1, 1, 3)))  # [-1, 0.0, 1.0]
print(list(numbers(0, 1, 3)))  # [0, 0.5, 1.0]
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
2

It seems like what you're looking for is np.linspace(), which you can read up about here.

For example, calling np.linspace(-1, 1, 3) will result in array([-1., 0., 1.]), as you wanted.

Alon Emanuel
  • 172
  • 3
  • 10
0

as noticed by Error this is the problem which can easily be solved without external packages, my solution below:

def partition(min,max,n):
    list=[]
    for i in range (n):
        list.append((max-min)*i/(n-1))
    return list
Igor sharm
  • 396
  • 1
  • 10
  • How is your proposed solution different from the one posted by Eugene above? All you have done is to change the variable names... – mnm Jun 20 '19 at 11:14
  • 1
    @mnm thanks for your comment, solutions were published at the same time(at least when i started to type there was none), I proposed it when I saw comment that it can be better to not use external libraries. Moreover even after finding out that similar solution was also posted I desided to keep this as, in my opinion, simple questions are mostly for learners and keeping it simple, without yield or assert operators may be reasonable for newbies to understand the code better. – Igor sharm Jun 20 '19 at 11:55