Skip to content Skip to sidebar Skip to footer

First Element Out Of Order On A List

For the list [1,4,6,8,2,10] it should return 2 For the list [1,6,7,9,3,10] it should return 3 It should return the first number that smaller then his last, first to be in wrong or

Solution 1:

Simply keep the last checked element in the list and check if the current element in the list is smaller or not.

def out_of_order(lst):
    before = 0
    for y in lst:
        if y < before:
            return y
        before = y

print(out_of_order([1,4,6,8,2,10]))
print(out_of_order([1,6,7,9,3,10]))

Solution 2:

Your second version is already correct - you just need to return the value rather than printing it:

def out_of_orders(lst):
    for a, b in zip(lst, lst[1:]):
        if b < a:
            return b

Solution 3:

See the answer of Christian Berendt for a faster solution.

The most important problem with your first code is that it should check lst[a] instead of a. A fix:

def out_of_order(lst):
    for a in range(0,len(lst)):
        for b in range(a+1,len(lst)):
            if(lst[b]<lst[a]):
                print(lst[b])
                return
    print("none")

out_of_order([1,6,7,9,3,10])

Post a Comment for "First Element Out Of Order On A List"