我正在开发一个项目,我需要在 python 中重新创建范围函数。我就在那儿。该函数的标题为 myRange()。到目前为止我有一份代码副本
numList = []
def myRange(start, stop=None, step=None):
if stop == None and step == None:
start, stop, step = 0, start, 1
while step <= stop:
numList.append(step-1)
step+=1
elif start < stop and step == None:
start, stop, step = start, stop, start
while step < stop:
numList.append(step)
step+=1
elif start > stop and step == None:
start, stop, step = start, stop, start
while start >= stop:
numList.append(step)
step -= 1
else:
start, stop, step = start, stop, step
while start < stop:
numList.append(start)
start+=step
return numList
print(myRange(90,80))
我目前正在尝试打印一个从 90 到 80 的递减列表。我卡住的地方在这里:
elif start > stop and step == None:
start, stop, step = start, stop, start
while start >= stop:
numList.append(step)
step -= 1
这应该起作用,即开始大于停止,并且没有指示步骤,它应该附加步骤的值(分配给开始的值)然后它应该从设置的步骤减一,并添加numList 的下一个值。为什么这不是这样工作的?
有一些问题:
您写下想要使用
myRange(90,80)
获得递减列表,但这不是该调用的预期输出。本机函数 range(90,80)
将返回一个空范围,因为步长默认为 1。您不应该仅仅因为 start > stop
就决定步长为 -1。这不应该是这样的。获得否定步骤的唯一方法是将其作为参数提供。
以下循环有问题:
while start >= stop:
numList.append(step)
step -= 1
因为无论您执行多少次
start >= stop
,条件step -= 1
始终为真。这不会影响循环条件。因此,最终该进程会抛出异常——当由于数百万次调用numList.append
而导致内存不足时。
当使用负步骤调用该函数时,将执行最后一个块,但
while
条件是错误的。如果步长为负,则应为 while start > stop
。因此,myRange(2, 0, -1)
将返回一个空列表,但它应该返回[2, 1]
。
numList
不应该是全局名称。正如您现在所看到的,第二次调用 myRange
不会重置该列表,而只是进一步扩展它。还有一个问题是,每次调用 myRange
都会返回 same 单个列表对象。你永远只有一张清单。这是错误的。每次调用 myRange
都应该返回一个不同的列表,与之前的调用返回的内容无关。所以 numList
应该是一个 local 名称。
当第三个参数为 0 时,本机
range
将引发异常。您也许也应该实现它。
函数声明不应将
None
作为 step
的默认值,因为实际上默认值是 1。
您有不同的方法来确定要附加的值。有时
step-1
,有时step
,有时start
。这应该更好地协调。如果要在列表中放入一个值,第一个值将始终是start
的值(考虑到如果只提供一个参数,start
将为0)。因此,在 start
调用中始终使用 append
并在循环中使用 start += step
是有意义的。
更正如下:
# The default for step is 1, not None
def myRange(start, stop=None, step=1):
# Deal with the case where only one argument is provided:
if stop is None:
# In that case it should be taken as the value for stop
start, stop = 0, start
# Treat the invalid value for step
if step == 0:
raise ValueError("myRange step cannot be 0")
result = [] # A local name!
if step > 0: # The loop condition depends on the sign of the step
while start < stop:
result.append(start)
start += step
else:
while start > stop:
result.append(start)
start += step
return result