'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.



Solution 1:[1]

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.

Solution 2:[2]

if is_sorted(s[1:]) is True, then s[0]<is_sorted(s[1:]) is true only when s[0]<True which is equivalent to s[0] < 1

Solution 3:[3]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Darth Kotik
Solution 3 Michael Murphy