Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Recursion Functions

Recursive function to check if a list is sorted - Python Program

Example 1 :

def is_sorted(lst): """Check if list is sorted recursively.""" if len(lst) <= 1: return True return lst[0] <= lst[1] and is_sorted(lst[1:]) print(is_sorted([1, 2, 3, 4]))

Output

 
OUTPUT  :
True

Example 2 :

def is_sorted_recursive(lst): """ Recursively checks if a list is sorted in ascending order. Args: lst: The list to check. Returns: True if the list is sorted, False otherwise. """ # Base case: An empty list or a list with one element is considered sorted. if len(lst) <= 1: return True # Recursive step: Check if the first two elements are in order # and recursively check the rest of the list (from the second element onwards). if lst[0] <= lst[1]: return is_sorted_recursive(lst[1:]) else: return False # Test cases list1 = [1, 2, 3, 4, 5] list2 = [1, 3, 2, 4, 5] list3 = [] list4 = [7] list5 = [5, 5, 5] print(f"Is {list1} sorted? {is_sorted_recursive(list1)}") print(f"Is {list2} sorted? {is_sorted_recursive(list2)}") print(f"Is {list3} sorted? {is_sorted_recursive(list3)}") print(f"Is {list4} sorted? {is_sorted_recursive(list4)}") print(f"Is {list5} sorted? {is_sorted_recursive(list5)}")

Output

 
OUTPUT  :
Is [1, 2, 3, 4, 5] sorted? True
Is [1, 3, 2, 4, 5] sorted? False
Is [] sorted? True
Is [7] sorted? True
Is [5, 5, 5] sorted? True