简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM