Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to see if the list contains consecutive numbers

Tags:

python

list

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 return True.

How should I check if the list contains up to n consecutive numbers without modifying the original list? I thought about copying the list and removing each number that appears in the original list and if the list is empty then it will return True.

Is there a better way to do this?

like image 450
allmine Avatar asked Nov 06 '15 20:11

allmine


2 Answers

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])
like image 69
wnnmaw Avatar answered Sep 21 '22 13:09

wnnmaw


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
like image 43
Shankar Avatar answered Sep 20 '22 13:09

Shankar