Dec 27, 2011

xrange with float steps - Python

The great thing about this code, is that the definition its a generator. (You can easily identify the keyword yield)

def drange(start, stop, step):
    r = start
    while r < stop:
        yield r
        r += step

>>>i0=drange(0.0, 1.0, 0.1)
>>>["%g" % x for x in i0]
['0', '0.1', '0.2', '0.3', '0.4', '0.5', '0.6', '0.7', '0.8', '0.9', '1']
>>>

source

No comments: