Efficient way to find missing elements in an integer sequence

前端 未结 16 1373
鱼传尺愫
鱼传尺愫 2020-12-01 04:32

Suppose we have two items missing in a sequence of consecutive integers and the missing elements lie between the first and last elements. I did write a code that does accomp

16条回答
  •  猫巷女王i
    2020-12-01 05:16

    We found a missing value if the difference between two consecutive numbers is greater than 1:

    >>> L = [10,11,13,14,15,16,17,18,20]
    >>> [x + 1 for x, y in zip(L[:-1], L[1:]) if y - x > 1]
    [12, 19]
    

    Note: Python 3. In Python 2 use itertools.izip.

    Improved version for more than one value missing in a row:

    >>> import itertools as it
    >>> L = [10,11,14,15,16,17,18,20] # 12, 13 and 19 missing
    >>> [x + diff for x, y in zip(it.islice(L, None, len(L) - 1),
                                  it.islice(L, 1, None)) 
         for diff in range(1, y - x) if diff]
    [12, 13, 19]
    

提交回复
热议问题