How to see if the list contains consecutive numbers

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

    The input to this function is your list.This function returns False if the numbers are repeated. The below code works even if the list does not start with 1.

    def check_is_consecutive(l):
        """
        sorts the list and 
        checks if the elements in the list are consecutive
        This function does not handle any exceptions.
        returns true if the list contains consecutive numbers, else False
        """
        l = list(filter(None,l))
        l = sorted(l)
        if len(l) > 1:
            maximum = l[-1]
            minimum = l[0] - 1
            if minimum == 0:
                if sum(l) == (maximum * (maximum+1) /2): 
                    return True
                else:
                    return False
            else:
                if sum(l) == (maximum * (maximum+1) /2) - (minimum * (minimum+1) /2) : 
                    return True
                else:
                    return False
        else:
            return True
    

提交回复
热议问题