Skip to content Skip to sidebar Skip to footer

How To See If The List Contains Consecutive Numbers

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

Solution 1:

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:

defcheck(n, l):
    subs = [l[i:i+n] for i inrange(len(l)) iflen(l[i:i+n]) == n]
    returnany([(sorted(sub) inrange(min(l), max(l)+1)) for sub in subs])

Solution 2:

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) /2defcheck_is_consecutive(l):
        maximum = max(l)
        ifsum(l) == maximum * (maximum+1) /2 : 
             returnTruereturnFalse

Solution 3:

The first code removes duplicates but keeps order:

from itertools import groupby, count

l = [1,2,4,5,2,1,5,6,5,3,5,5]

defremove_duplicates(values):
    output = []
    seen = set()
    for value in values:
        if value notin seen:
            output.append(value)
            seen.add(value)
    return output

l = remove_duplicates(l) # output = [1, 2, 4, 5, 6, 3]

The next set is to identify which ones are in order, taken from here:

defas_range(iterable):
    l = list(iterable)
    iflen(l) > 1:
        return'{0}-{1}'.format(l[0], l[-1])
    else:
        return'{0}'.format(l[0])

l = ','.join(as_range(g) for _, g in groupby(l, key=lambda n, c=count(): n-next(c)))

l outputs as: 1-2,4-6,3

You can customize the functions depending on your output.

Solution 4:

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

defcheck(l):
    total = 0
    minimum = float('+inf')
    maximum = float('-inf')

    seen = set()

    for n in l:
        if n in seen:
            returnFalse

        seen.add(n)

        if n < minimum:
            minimum = n

        if n > maximum:
            maximum = n

        total += n

    if2 * total != maximum * (maximum + 1) - minimum * (minimum - 1):
        returnFalsereturnTrue

Solution 5:

import numpy as np
import pandas as pd    

(sum(np.diff(sorted(l)) == 1) >= n) & (all(pd.Series(l).value_counts() == 1))

We test both conditions, first by finding the iterative difference of the sorted list np.diff(sorted(l)) we can test if there are n consecutive integers. Lastly, we test if the value_counts() are all 1, indicating no repeats.

Post a Comment for "How To See If The List Contains Consecutive Numbers"