1

Hi there, I found this really helpful topic on finding missing elements in a list of integers.
I found the second answer most useful and am applying it now to my code:

def missing_elements(X):
    start, end = X[0], X[-1]
    return sorted(set(range(start, end + 1)).difference(X))

Now, the problem is that I do not have a list, but a series of list of which this is a snapshot:

[716, 717, 718, 719, 720, 721]
[761, 762, 763, 764, 765, 766, 767, 768]
[988, 989, 990, 993, 994]

I would like to see as a result something like:

[0]
[0]
[991, 992]

Obviously, the above code is not working. But I have no idea of how to get it working. I get the impression that I might want to make this into a set and do something with set type features, but that's only a guess...

Community
  • 1
  • 1
Davidva
  • 27
  • 1
  • 2
    The code above is working. See http://ideone.com/GhbqGv Applying this function to a list of lists is easy: either use `for a in list_of_lists: print missing_elements(a)` or `map` – Konstantin Jun 09 '16 at 10:07
  • You just forget to add indentation for lines in function. It is work fine. – Serenity Jun 09 '16 at 10:10

2 Answers2

1

First off, as a more pythonic way you can use following function in order to detect your missing items, then use a list comprehension to apply the function on your lists:

>>> from itertools import chain
>>> def missing(iterable):
...     return chain.from_iterable(range(i+1, j) for i, j in zip(iterable, iterable[1:]) if j > i + 1)

Demo :

>>> lst = [[716, 717, 718, 719, 720, 721],
... [761, 762, 763, 764, 765, 766, 767, 768],
... [988, 989, 990, 993, 994]]
... 
>>> [list(missing(i)) for i in lst]
[[], [], [991, 992]]
>>> 

Here is a benchmark with your suggested function, that shows this function is almost 2 time faster:

~ $ python -m timeit --setup "from itertools import chain; iterable=range(100)" "chain.from_iterable(range(i+1, j) for i, j in zip(iterable, iterable[1:]) if j > i + 1)"
100000 loops, best of 3: 3.68 usec per loop
~ $ python -m timeit --setup "iterable=range(100)" "start, end = iterable[0], iterable[-1]; sorted(set(range(start, end + 1)).difference(iterable))"
100000 loops, best of 3: 6.94 usec per loop
Mazdak
  • 105,000
  • 18
  • 159
  • 188
1

Just map your existing function onto the series of lists:

> lsts = [[716, 717, 718, 719, 720, 721],
          [761, 762, 763, 764, 765, 766, 767, 768],
          [988, 989, 990, 993, 994]]
> map(missing_elements, lsts)
[[], [], [991, 992]]
user2390182
  • 72,016
  • 6
  • 67
  • 89