Reputation: 61
What I need is to divide/spread 0 to 1. according to single number which is more than 2. like number 5 will be divided like this
0.00
0.25
0.50
0.75
1.00
5 values in a list
and my other question is what to do to get a sequence like this where middle number is 1 and first and last number is 0 , if number is 10.
0.00
0.25
0.50
0.75
1.00
1.00
0.75
0.50
0.25
0.00
10 item in list how to this in python via loop ?
Upvotes: 0
Views: 61
Reputation: 2830
From the numpy linspace documentation:
Return evenly spaced numbers over a specified interval.
Exactly what we need to solve your first problem.
import numpy as np
def spread(n):
return np.linspace(0, 1, n)
For the second question we can just reuse the array from the first question, invert it and append it. We just have to integer divide //
your number by 2 (assuming it is divisible by 2) to get the number to pass to spread
. You get a reverse version of a list/tuple/numpy array doing the following:
my_list[::-1]
So your function would look something like:
import numpy as np
def updown(n):
first_half = spread(n//2)
return np.r_[first_half, first_half[::-1]]
You could also flip the array using np.flipud and instead of np.r_ you could use np.concatenate:
import numpy as np
def updown(n):
first_half = spread(n//2)
return np.concatenate((first_half, np.flipud(first_half)))
Or if you do not need arrays in the end you could do (the same as in a different answer):
import numpy as np
def spread(n):
return list(np.linspace(0, 1, n))
def updown(n):
first_half = spread(n//2)
return first_half + first_half[::-1]
Upvotes: 2
Reputation: 46859
the first part is easy:
def spread(n):
return tuple(i/(n-1) for i in range(n))
and with that you can create the second by concatenating the tuple from above with the reversed tuple:
def updown(n):
tpl = spread(n//2)
return tpl + tpl[::-1]
if n
is odd updown(n)
will be the same as updown(n-1)
...
Upvotes: 1