Home > OS >  Is there a way to check each following element in the list against the previous in order to see if a
Is there a way to check each following element in the list against the previous in order to see if a

Time:12-08

I'm trying to write a program that takes a list given by a user, checks if it is/isn't in decreasing order and print out an appropriate statement. The program works okay if I input values which are/aren't in decreasing order such as [5,4,3,2,1] or [1,2,3,4,5]. However, if I input something like [5,4,5,4,3,2,1] or [1,2,1,2,3,4,5] it will still say the list is/isn't in decreasing order. I imagine it's because the way I have my code written it's only comparing the first item in the list to the second, or something like that. But I haven't for the life of me being able to figure out how to compare each item in the list to the next so that the program is accurate.

def decreasingOrder():
    element = 0
    integer_list = []

    userInput = input("Please enter your numbers seperated by a comma (,):")
    inputtedStrings = userInput.split(",")
    for number in inputtedStrings:
        inputtedIntegers = int(number)
        integer_list.append(inputtedIntegers)

    if integer_list[element] > integer_list[element-1]:
        print("The list is in decreasing order.")
    else:
        print("The list is not in decreasing order.") 

    
        

decreasingOrder()

    
            

That's the code. As previously stated, the program should print "The list is in decreasing order." if the list is in decreasing order, and "The list is not in decreasing order." if the list isn't.

CodePudding user response:

A different approach. Use the sorted function and test for increasing or decreasing.

def decreasingOrder():
    element = 0
    integer_list = []
    userInput = input("Please enter your numbers seperated by a comma (,):")
    inputtedStrings = userInput.split(",")
    for number in inputtedStrings:
        inputtedIntegers = int(number)
        integer_list.append(inputtedIntegers)
    increasing = integer_list == sorted(integer_list)
    decreasing = integer_list == sorted(integer_list, reverse=True)

    if decreasing:
        print("The list is in decreasing order.")
    elif increasing:
        print("The list is not in decreasing order.")
    else:
        print("The list is mixed neither increasing or decreasing order.")


decreasingOrder()

CodePudding user response:

You can use the zip() function to check each element with its successor and determine if they are all greater (which means the list is in decreasing order):

list1 = [100,50,10,5,1]

if all(a>b for a,b in zip(list1,list1[1:])):
    print("list1 is in decreasing order")     # <--
else:
    print("list1 is not in decreasing order")

list2 = [100,5,10,5,1]

if all(a>b for a,b in zip(list2,list2[1:])):
    print("list2 is in decreasing order")
else:
    print("list2 is not in decreasing order") # <--
  • Related