【发布时间】:2020-07-20 02:43:31
【问题描述】:
这个函数只返回 1 的值。有人可以帮忙吗?这些参数描述了我正在尝试实现的内容,但我不确定为什么会发生这种情况。
def clamp(alist,min,max):
"""
MODIFIES the list so that every element is between min and max.
Any number in the list, less than min is replaced with min. Any
number in the list greater than max is replaced with max. Any number
between min and max is left unchanged.
This is a PROCEDURE. It modifies alist, but does not return a new
list.
Example: if alist is [-1, 1, 3, 5], then clamp(thelist,0,4) changes
alist to have [0,1,3,4] as its contents.
Parameter alist: the list to modify
Precondition: alist is a list of numbers (float or int)
Parameter min: the minimum value for the list
Precondition: min <= max is a number
Parameter max: the maximum value for the list
Precondition: max >= min is a number
"""
alist.append(min)
alist.append(max)
for a in alist:
if max >= a >= min:
return a
alist.sort()
return alist
返回:1,无论输入。
【问题讨论】:
-
您不能将条件语句串在一起。使用
max >= a and a >= min -
在两行或 1 行中,因为我尝试了 1 行,但仍然得到相同的响应。而且我认为 if 语句的语句不能使用两行。
-
什么是
thelist保持参数一致,它应该是clamp(alist, 0,4)而不是thelist,它没有在任何地方定义。您不必将min和max附加到alist,如果您正在检查已填充列表中的值,只需比较值而不是附加然后replace()值并排序列表。 -
对不起,这个列表是个意外,它应该是
alist,但这在函数描述中,而不是代码的一部分。那只是指一个已经在终端中定义的假设列表。 -
如果您只是创建一个列表,其中每个元素都在一个范围内“固定”,那么就无法理解
alist.append(min), alist.append(max) and alist.sort()调用的目的。此外,min 和 max 也不是好的变量名,因为它替换了内置函数,从而使代码审查者感到困惑。
标签: python conditional-statements