How to see if the list contains consecutive numbers

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

    Once you verify that the list has no duplicates, just compute the sum of the integers between min(l) and max(l):

    def check(l):
        total = 0
        minimum = float('+inf')
        maximum = float('-inf')
    
        seen = set()
    
        for n in l:
            if n in seen:
                return False
    
            seen.add(n)
    
            if n < minimum:
                minimum = n
    
            if n > maximum:
                maximum = n
    
            total += n
    
        if 2 * total != maximum * (maximum + 1) - minimum * (minimum - 1):
            return False
    
        return True
    

提交回复
热议问题