Home > database >  How to find Where a List First Went out of Order in Python
How to find Where a List First Went out of Order in Python

Time:10-30

I'm writing this program at school where my teacher wants us to enter 5 numbers into a list, and if the list of numbers is not in order of least to greatest, it is to say where the list first went out of order.

My code:

#Function Definititions
def start():
  list = []
  for i in range(0,5):
    number = int(input("Enter a number: "))
    list.append(number)
  flag = 0
  i = 1
  while i < len(list):
      if(list[i] < list[i-1]):
          flag = 1
      i  = 1
  if(not flag) :
    print("This list of numbers is true.")
  else:
    print("This list of numbers is false. List became out of order at", )
    list = sorted(list, reverse=False) 
    print("True Version:",list)
  return flag

#Main Program
start1 = start()

I wanna say where a list like, for example, 10,4,5,8,10 went out of order first, which would be at list[0] in that particular case. I can't add any shortcut functions already built into Python, and the part where my code says print("This list of numbers is false. List became out of order at", ) is where I wanna add it, which is why I left it blank in my program. Everything else in my program works fine, so it wouldn't matter too much if a solution can't be found, but if anyone does know what to do, I am all ears.

CodePudding user response:

Something like this

# Function Definitions
def start():
    my_list = []
    for i in range(0, 5):
        number = int(input("Enter a number: "))
        my_list.append(number)
    flag = False
    i = 1
    while i < len(my_list):
        if my_list[i] < my_list[i - 1]:
            # found out of order element
            flag = True
            print(f'Out of order at {my_list[i - 1]}')  # print the element
            break  # no need to continue
        i  = 1
    if not flag:
        print("This list of numbers is true.")
    return flag


# Main Program
start1 = start()
  • Related