How to see if the list contains consecutive numbers

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

    We can use known mathematics formula for checking consecutiveness, Assuming min number always start from 1

    sum of consecutive n numbers 1...n = n * (n+1) /2 
    
    
      def check_is_consecutive(l):
            maximum = max(l)
            if sum(l) == maximum * (maximum+1) /2 : 
                 return True
            return False
    

提交回复
热议问题