Basically I want to go from -1 to 1 in n
steps, including -1 and 1:
x = -1.0
n = 21
for i in range(n):
print x
x += 0.01
-1.0 -0.9 -0.8 ... 0.8 0.9 1.0
How can I write this in the most elegant, simplest way for any n
value?
for in Loop: For loops are used for sequential traversal. For example: traversing a list or string or array etc. In Python, there is no C style for loop, i.e., for (i=0; i<n; i++).
map() works way faster than for loop.
There is no built-in solution, but probably a good way to solve it is to define your own range
function:
def my_range(start, end, how_many):
incr = float(end - start)/(how_many - 1)
return [start + i*incr for i in range(how_many)]
And you can use it in a for-loop:
>>> for i in my_range(-1, 1, 10):
... print i
...
-1.0
-0.777777777778
-0.555555555556
-0.333333333333
-0.111111111111
0.111111111111
0.333333333333
0.555555555556
0.777777777778
1
EDIT: As @NiklasBaumstark suggested, if your brand new my_range
function is going to handle a big quantity of numbers it is probably a good idea to use generators. For that purpose, we'll do just a little modification:
def my_xrange(start, end, how_many):
incr = float(end - start)/(how_many - 1)
return (start + i*incr for i in xrange(how_many))
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