Second argument of three mandatory

前端 未结 1 1545
醉梦人生
醉梦人生 2021-01-27 14:33

I have a function that mimics range(). I am stuck at one point. I need to be able to make the first (x) and third (step) arguments optional, but the middle argument (y) mandat

相关标签:
1条回答
  • 2021-01-27 15:04

    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]
    
    0 讨论(0)
提交回复
热议问题