简体   繁体   中英

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? 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. (This is slightly obscured because python auto-converts the boolean to an integer (0 or 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM