How to see if the list contains consecutive numbers

后端 未结 12 1413
别跟我提以往
别跟我提以往 2021-02-07 12:50

I want to test if a list contains consecutive integers and no repetition of numbers. For example, if I have

l = [1, 3, 5, 2, 4, 6]

It should re

12条回答
  •  庸人自扰
    2021-02-07 13:14

    I split your query into two parts part A "list contains up to n consecutive numbers" this is the first line if len(l) != len(set(l)):

    And part b, splits the list into possible shorter lists and checks if they are consecutive.

    def example (l, n):
        if len(l) != len(set(l)):  # part a
            return False
        for i in range(0, len(l)-n+1):  # part b
            if l[i:i+3] == sorted(l[i:i+3]):
                return True
        return False
    
    l = [1, 3, 5, 2, 4, 6]
    print example(l, 3)
    

提交回复
热议问题