简体   繁体   中英

What is the way to get the starting and ending index from an input list of unique numbers from 1 to 8 which are not in ascending order

i am trying to find out how i can find the starting and ending index with input constraints that the list should contain non repeating numbers from 1 to 8 only. if the numbers are not in ascending order like [1,2,4,5,3,7,6,8], starting index and ending index should be 2 and 6. My code is below

x = [int(i) for i in input().split()]
k = len(x)
for i in range(len(x)):
    if x[i] != i+1:
        print(i)
        break
for i in range(k-1,0,-1):
    if x[k-1] != i+1:
        print(i)
        break
    k -=1

So you are trying to find the earliest index that conforms to ascending order, from both ends of the list.

You can use a list comprehension to check if each element is what it is supposed to be

x = list(map(int, input.split())) # another way to process the input
is_correct = [e == i+1 for i, e in enumerate(x)] # returns a boolean list
start = is_correct.index(False)
end = len(x) - is_correct.reverse().index(False) - 1

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