尝试使用我的 is_descending() 函数时不了解类型错误的原因



函数is_descending,它接受一个参数列表,并检查它是否是一个降序,即列表中的第一个元素必须大于第二个,第二个大于第三个,第三个大于第四个,等等。返回值为True/False

def is_descending(a):
for i in range(len(a) - 1):
if a[i] < a[i + 1]:
return False
elif a[i] > a[i + 1]:
return True

assert is_descending(3, 4) == False
assert is_descending(5, 5) == False
assert is_descending(10, 1) == True
assert is_descending(10, 8, 7, 6, 1, -10, -20) == True
assert is_descending(10, 8, 7, 6,6, 1, -10, -20) == False
assert is_descending(1) == True

终端写入:

TypeError: is_descending() takes 1 positional argument but 2 were given

关于如何编辑我的代码有什么建议吗?我只想使用一个参数。

您的函数需要a是一个列表。使用is_descending([3, 4])而不是传递2个参数(2个整数(的is_descending(3, 4)

此外,只有在检查完整个列表后,函数才会返回True。这里只有第一次检查很重要,因为使用return停止循环而不检查其他值对。

相反,您可以删除elif块,并在for循环之外返回True,以等待所有检查成功通过。

实现这一点的一个更简单的方法是检查列表是否按相反的顺序排序(即排序后是否发生变化(:

def is_reversed(a):
return a == sorted(a, reverse=True)

最新更新