尝试使用我的 is_descending() 函数时不明白 TypeError 的原因
函数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
关于如何编辑我的代码的任何建议?我只想使用1个参数。
Function is_descending, which accepts one parameter list and checks if it is a descending sequence i.e. the first element in the list must be bigger than the second, the second bigger than the third, the third bigger than the fourth, etc... The return value is 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
terminal writes:
TypeError: is_descending() takes 1 positional argument but 2 were given
Any advice on how to edit my code? I want to work with only 1 parameter.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的功能需要
a
作为列表。而不是通过2个参数(2个整数),而不是
is_descending(3,4)
,请使用is_descending([3,4])
。此外,只有在检查整个列表后,该功能才应返回true。在这里,只有第一个检查很重要,因为
返回
在不检查其他值的情况下停止循环。取而代之的是,您可以删除
elif
块,然后在for循环之外返回true,以等待成功传递的所有检查。实现此目的的一种更简单的方法是检查列表是否以相反的顺序排序(即对其进行分类后会更改):
Your function needs
a
to be a list.Instead of
is_descending(3, 4)
that passes 2 parameters (2 integers), useis_descending([3, 4])
.Also the function should only return True once the whole list has been checked. Here only the first check matters as using
return
stops the loop without checking for other pairs of values.Instead you can remove the
elif
block and return True outside of the for loop to wait for all the checks to be passed successfully.Also a simpler way to achieve this would be to check if the list is sorted in reversed order (i.e. does it change after being sorted):