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
>Solution :
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]