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