Second argument of three mandatory

谁说胖子不能爱 提交于 2019-12-09 03:51:58

问题


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) mandatory. In the code below, everything works except the two commented out lines.

If I am only passing in one argument, how do I construct the function to accept the single passed in argument as the mandatory (y) argument?

I cannot do this: def float_range(x=0, y, step=1.0):

Non-default parameter cannot follow a default parameter.

def float_range(x, y, step=1.0):
    if x < y:
        while x < y:
            yield x
            x += step
    else:
        while x > y:
            yield x
            x += step


for n in float_range(0.5, 2.5, 0.5):
    print(n)

print(list(float_range(3.5, 0, -1)))

for n in float_range(0.0, 3.0):
    print(n)

# for n in float_range(3.0):
#     print(n)

Output:

0.5 1.0 1.5 2.0 [3.5, 2.5, 1.5, 0.5] 0.0 1.0 2.0


回答1:


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]


来源:https://stackoverflow.com/questions/51250476/second-argument-of-three-mandatory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!