[英]A recursive function to check if a list of int are sorted in Ascending order
def is_sorted(s):
if s==[]:
return True
else:
return s[0]<is_sorted(s[1:])
Calling this function should get: 调用此函数应该得到:
#1 is_sorted([])-->True
#2 is_sorted([1,2,3,4,5,6,7])-->True
#3 is_sorted([1,2,3,7,4,5,6])-->False
But my function always return False instead of True on #2, can someone please point out the problem of my function? 但是我的函数总是在#2上返回False而不是True,有人可以指出我的函数问题吗? Thank you. 谢谢。
The problem is that you're comparing s[0]
which is an integer, to the return value of is_sorted(s[1:])
, which is a boolean. 问题是你将s[0]
(一个整数)与is_sorted(s[1:])
的返回值进行is_sorted(s[1:])
,这是一个布尔值。 (This is slightly obscured because python auto-converts the boolean to an integer (0 or 1)) (这有点模糊,因为python将布尔值自动转换为整数(0或1))
Your return value must be a boolean (specified in the output), so you need to come up with different comparisons and a different recursive call. 您的返回值必须是布尔值(在输出中指定),因此您需要进行不同的比较和不同的递归调用。
Here is a working version of your code: 这是您的代码的工作版本:
def is_sorted(s):
if len(s) in [0,1]:
return True
if s[0] <= s[1]:
return is_sorted(s[1:])
return False
如果is_sorted(s[1:])
为True
,则s[0]<is_sorted(s[1:])
仅在s[0]<True
等于s[0] < 1
As pjz said, your problem is your boolean comparison after your else statement. 正如pjz所说,你的问题是你的else语句之后的布尔比较。 Try something along the lines of looping over each element in the list and checking of each number is bigger than the last. 尝试循环遍历列表中每个元素的行,并检查每个数字是否大于最后一个。 You may also want to check if each number is numeric and return false of not. 您可能还想检查每个数字是否为数字,并返回false。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.