First element out of order on a list

2019-08-09 02:59发布

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 order.

How should I do it? this what I wrote, in 2 versions. I've been working on this whole day with no success.

#1 version

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

#2 version

def out_of_orders(lst):
    for a,b in zip(lst,lst[1:]):
        if(b<a):
            print(b)
            break
        else:
            print("none")

标签: python
3条回答
虎瘦雄心在
2楼-- · 2019-08-09 03:46

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]))
查看更多
姐就是有狂的资本
3楼-- · 2019-08-09 03:46

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])
查看更多
我命由我不由天
4楼-- · 2019-08-09 03:56

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
查看更多
登录 后发表回答