Second argument of three mandatory

偶尔善良 提交于 2019-12-02 11:52:51

You have to use sentinel values:

def float_range(value, end=None, step=1.0):
    if end is None:
        start, end = 0.0, value
    else:
        start = value

    if start < end:
        while start < end:
            yield start
            start += step
    else:
        while start > end:
            yield start
            start += step

for n in float_range(0.5, 2.5, 0.5):
    print(n)
#  0.5
#  1.0
#  1.5
#  2.0

print(list(float_range(3.5, 0, -1)))
#  [3.5, 2.5, 1.5, 0.5]

for n in float_range(0.0, 3.0):
    print(n)
#  0.0
#  1.0
#  2.0

for n in float_range(3.0):
    print(n)
#  0.0
#  1.0
#  2.0

By the way, numpy implements arange which is essentially what you are trying to reinvent, but it isn't a generator (it returns a numpy array)

import numpy

print(numpy.arange(0, 3, 0.5))
# [0.  0.5 1.  1.5 2.  2.5]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!