python - How do I use a decimal step value for range()? - Stack Overflow
[Python] What does -1 do in a range function?
list slicing parameters: where is 'step' in the docs?
How to round to the nearest 0.5 in python?
This should work: round(x*2)/2
Videos
Rather than using a decimal step directly, it's much safer to express this in terms of how many points you want. Otherwise, floating-point rounding error is likely to give you a wrong result.
Use the linspace function from the NumPy library (which isn't part of the standard library but is relatively easy to obtain). linspace takes a number of points to return, and also lets you specify whether or not to include the right endpoint:
>>> np.linspace(0,1,11)
array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ])
>>> np.linspace(0,1,10,endpoint=False)
array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
If you really want to use a floating-point step value, use numpy.arange:
>>> import numpy as np
>>> np.arange(0.0, 1.0, 0.1)
array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
Floating-point rounding error will cause problems, though. Here's a simple case where rounding error causes arange to produce a length-4 array when it should only produce 3 numbers:
>>> numpy.arange(1, 1.3, 0.1)
array([1. , 1.1, 1.2, 1.3])
range() can only do integers, not floating point.
Use a list comprehension instead to obtain a list of steps:
[x * 0.1 for x in range(0, 10)]
More generally, a generator comprehension minimizes memory allocations:
xs = (x * 0.1 for x in range(0, 10))
for x in xs:
print(x)
What is happening here for example? It doesn't make sense to me.
for i in range(len(word1)-1, -1, -1):
for j in range(len(word2) -1, -1, -1):Wouldn't this be invalid? Getting the range -1 to -1, going -1 at a time? Is that whats happening?
Is this subtracting 1 from the range on each iteration? How come its formatted this way if so? Wouldnt it be (len(word1)-1) if they were trying to do that? These parameters don't make sense. Help?