How to find out if a list contains consecutive numbers

I want to check if the list contains consecutive integers and there is no repetition of numbers. For example, if I have

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

Must return True.

How can I check if a list contains up to n consecutive numbers without changing the original list? I was thinking about copying the list and deleting every number that appears in the original list, and if the list is empty, it will return True.

Is there a better way to do this?

+9
source share
9 answers

For the whole list, it should be as simple as

sorted(l) == list(range(min(l), max(l)+1))

This keeps the original list, but making a copy (and then sorting) can be expensive if your list is especially long.

, Python 2 , range list. 3.x , range, sorted(l) list

sorted(l) == range(min(l), max(l)+1))

, n , :

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])
+13

, , 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
+4

, , min(l) 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
+1
import numpy as np
import pandas as pd    

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

, , np.diff(sorted(l)), , n . , , value_counts() - 1, .

+1

, :

from itertools import groupby, count

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

def remove_duplicates(values):
    output = []
    seen = set()
    for value in values:
        if value not in seen:
            output.append(value)
            seen.add(value)
    return output

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

- , , :

def as_range(iterable):
    l = list(iterable)
    if len(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 : 1-2,4-6,3

.

0

: " n ", if len(l) != len(set(l)):

b , .

def example (l, n):
    if len(l) != len(set(l)):  # part a
        return False
    for i in range(0, len(l)-n+1):  # part b
        if l[i:i+3] == sorted(l[i:i+3]):
            return True
    return False

l = [1, 3, 5, 2, 4, 6]
print example(l, 3)
0
def solution(A):
    counter = [0]*len(A)
    limit = len(A)
    for element in A:
        if not 1 <= element <= limit:
            return False
        else:
            if counter[element-1] != 0:
                return False
            else:
                counter[element-1] = 1

    return True
0

- . False, . , 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
0

, :

range = range(10)
L = [1,3,5,2,4,6]
L = sorted(L, key = lambda L:L)
range[(L[0]):(len(L)+L[0])] == L

>>True

. , , , (, ) . , , / , , , .

-1

Source: https://habr.com/ru/post/1614799/


All Articles