How to see if the list contains consecutive numbers

后端 未结 12 1390
别跟我提以往
别跟我提以往 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:09

    For the whole list, it should just be as simple as

    sorted(l) == list(range(min(l), max(l)+1))
    

    This preserves the original list, but making a copy (and then sorting) may be expensive if your list is particularly long.

    Note that in Python 2 you could simply use the below because range returned a list object. In 3.x and higher the function has been changed to return a range object, so an explicit conversion to list is needed before comparing to sorted(l)

    sorted(l) == range(min(l), max(l)+1))
    

    To check if n entries are consecutive and non-repeating, it gets a little more complicated:

    def check(n, l):
        subs = [l[i:i+n] for i in range(len(l)) if len(l[i:i+n]) == n]
        return any([(sorted(sub) in range(min(l), max(l)+1)) for sub in subs])
    

提交回复
热议问题