SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Y Daniel Lang
Chapter:
0.lists
Exercise:
Programming Excercises
Question:15 | ISBN:978013274719 | Edition: 6

Question

(Sorted?) Write the following function that returns true if the list is already sorted in increasing order:
                def isSorted(lst):
Write a test program that prompts the user to enter a list and displays whether the list is sorted or not.

Here is a sample run:

Enter list: 1 1 3 4 4 5 7 9 10 30 11
The list is not sorted

Enter list: 1 1 3 4 4 5 7 9 10 30
The list is already sorted

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Program Code:

# Function to check if a list is sorted in increasing order
def isSorted(lst):
    # Iterate over each element in the list starting from the second element
    for i in range(1, len(lst)):
        # Check if the current element is less than the previous element
        if lst[i] < lst[i-1]:
            # If any element violates the increasing order, return False
            return False
    
    # If all elements are in increasing order, return True
    return True

# Test program
def main():
    # Prompt the user to enter a list of numbers separated by spaces
    num = input("Enter list: ")

    # Convert the input string to a list of numbers
    numbers = [int(num) for num in num.split()]

    # Call the isSorted function to check if the list is sorted
    if isSorted(numbers):
        print("The list is already sorted")
    else:
        print("The list is not sorted")

# Call the test program
main()

Executed Output 1:

Enter list: 1 1 3 4 4 5 7 9 10 30 11
The list is not sorted

Executed Output 2:

Enter list: 1 1 3 4 4 5 7 9 10 30
The list is already sorted

 

0 0

Discussions

Post the discussion to improve the above solution.