简体   繁体   English

一个递归函数,用于检查int列表是否按升序排序

[英]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: 问题:

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))

To fix: 修理:

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.

相关问题 使用python检查int列表是否按升序排列 - Check if int list in in ascending order with python 一次检查列表是否按升序或降序排序 - Check if list is sorted in either ascending or descending order in one pass 递归 function 检查元素是否在 SORTED 列表中 - A recursive function to check if element is in SORTED list 如何测试列表是否按升序排序 - How to test if a list is sorted in ascending order 传递给 matplotlib 时按升序排序的列表 - list sorted in ascending order when passed to matplotlib Function 必须返回大于等于的最小偶数的列表,按升序排列 - Function must return a list of the smallest even integers that are greater than or equal to, sorted into ascending order 如何检查排序和旋转的数组是升序还是降序? - How can I check if sorted and rotated array is in ascending or descending order? 检查整数列表中是否存在升序(Python) - Check if there is an ascending order in a list of list of integers (Python) 我不能使用sorted函数对两个元素元组列表按降序排列,然后在出现领带的情况下按字母升序排序 - I can't use the sorted function to sort a two elements tuple list in descending numerical order then in ascending alphabetical order in case of a tie 在按升序排序的整数列表中添加缺失的数字 - Add missing numbers in a list of integers sorted in ascending order
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM