Home > database >  How to check if list contains consecutive numbers Python
How to check if list contains consecutive numbers Python

Time:08-24

I have below list:

l = [1, 2, 3, 4, 10, 11, 12]

By looking at the above list, we can say it's not consecutive. In order to find that using python, we can use below line of code:

print(sorted(l) == list(range(min(l), max(l) 1)))
# Output: False

This gives output False because 5, 6, 7, 8, 9 are missing. I want to further extend this functionality to check how many integers are missing. Also to note, no duplicates are allowed in the list. For ex:

l = [1, 2, 3, 4, 10, 11, 12, 14]

output of above list should be [5, 1] because 5 integers are missing between 4 and 10 and 1 is missing between 12 and 14

CodePudding user response:

This answers the question from the comments of how to find out how many are missing at multiple points in the list. Here we assume the list arr is sorted and has no duplicates:

it1, it2 = iter(arr), iter(arr)
next(it2, None) # advance past the first element
counts_of_missing = [j - i - 1 for i, j in zip(it1, it2) if j - i > 1]
total_missing = sum(counts_of_missing)

The iterators allow us to avoid making an extra copy of arr. If we can be wasteful of memory, omit the first two lines and change zip(it1, it2) to zip(arr, arr[1:]):

counts_of_missing = [j - i - 1 for i, j in zip(arr, arr[1:]) if j - i > 1]

CodePudding user response:

I think this will help you

L = [1, 2, 3, 4, 10, 11, 12, 14]
C = []
D = True
for _ in range(1,len(L)):
    if L[_]-1!=L[_-1]:
        C.append(L[_]-L[_-1]-1)
        D = False
print(D)
print(C)

Here I have checked that a number at ith index minus 1 is equal to its previous index. if not then D = false and add it to list

CodePudding user response:

here is my attempt:

from itertools import groupby

l = [1, 2, 3, 4, 10, 11, 12, 14]

not_in = [i not in l for i in range(min(l),max(l) 1)]
missed = [sum(g) for i,g in groupby(not_in) if i]

>>> missed
'''
[5, 1]

CodePudding user response:

Total number of missing integers

If you assume that arr contains no duplicates, then you can write directly:

total_missing = max(arr) - min(arr)   1 - len(arr)

The first term, max(arr) - min(arr) 1, is the total number of integers in interval [min(arr), max(arr)]. The second term, len(arr), is the actual number of integers in the array.

The difference between these two terms is the number of missing integers.

Note that:

  • if arr is sorted, then max(arr) is equal to arr[-1] and min(arr) is equal to arr[0];
  • if arr might contain duplicates, the above remains true if you replace len(arr) with len(set(arr)).
  • Related