Solution Exercise 34

Write a function that determines whether or not a list of values is in sorted order (either ascending or descending). The function should return True if the list is already sorted. Otherwise it should return False. Write a main program that reads a list of numbers from the user and then uses your function to report whether or not the list is sorted.

Hint:
Make sure you consider these questions when completing this exercise: Is a list that is empty in sorted order? What about a list containing one element?

#With this solution we assume that both an empty list and a list with one item are sorted
def is_sorted(list_of_numbers):
    if sorted(list_of_numbers) == list_of_numbers:
        return True
    #Ok, not sorted ascending, lets check descending
    elif sorted(list_of_numbers, key=int, reverse=True) == list_of_numbers:
        return True
    #At this point we know it is not sorted
    return False

def main():
    list_of_numbers = []
    #We use this boolean to indicate that we are not done
    done = False
    while not done:
        number = int(input("Enter a number. Exit with 0: "))
        if number != 0:
            list_of_numbers.append(number)
        else:
            done = True
    print(is_sorted(list_of_numbers))

if __name__ == '__main__':
    main()