-3

Is there a way to generate a list with a specific start and stop, and just automatically adjust the steps with integers?

E.g. using range(0,25,6) I get [0, 6, 12, 18, 24], but I need to start with 0 and end with 25 strictly, approximating intermediate values ​​like [0, 6, 12, 19, 25] or [0, 6, 13, 19, 25].

Obviously the range that I need is much wider, so doing it manually is not an option, and it doesn't matter to get intermediate numbers with approximate steps as in the two examples.

  • Yes, with `numpy.linspace` – roganjosh Aug 31 '22 at 05:35
  • Does this answer your question? [Making a list of evenly spaced numbers in a certain range in python](https://stackoverflow.com/questions/6683690/making-a-list-of-evenly-spaced-numbers-in-a-certain-range-in-python) – Rabinzel Aug 31 '22 at 05:47
  • With numpy `[int(round(x)) for x in np.linspace(0, 25, 5)]` will give you `[0, 6, 12, 19, 25]`. The third parameter is the number of elements in the resulting array/list. – Matthias Aug 31 '22 at 08:01
  • Thanks @Matthias, that worked perfectly! Can this comment be put as best answer? (I'm new to this community). – Camilo Yañez Aug 31 '22 at 15:31

2 Answers2

0

Code:

import numpy as np
print(np.linspace(0, 25, num=6), "\n")

Output:

[ 0.  5. 10. 15. 20. 25.] 

The numpy.linspace() function returns number spaces evenly w.r.t interval. Similar to numpy.arange() function but instead of step it uses sample number.

Syntax :

numpy.linspace(start,
               stop,
               num = 50,
               endpoint = True,
               retstep = False,
               dtype = None)

Parameters :

-> start  : [optional] start of interval range. By default start = 0
-> stop   : end of interval range
-> restep : If True, return (samples, step). By default restep = False
-> num    : [int, optional] No. of samples to generate
-> dtype  : type of output array

Return :

-> ndarray
-> step : [float, optional], if restep = True
Mehmaam
  • 573
  • 7
  • 22
0
import numpy as np   
import math  
start=0  
end=25  
step=6  
n = math.ceil((end-start+1)/step)  
x=np.linspace(start,end,n)  
ans=list(map(lambda y: int(y),x))