Efficient way to find missing elements in an integer sequence

前端 未结 16 1352
鱼传尺愫
鱼传尺愫 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条回答
  •  既然无缘
    2020-12-01 05:28

    Using scipy lib:

    import math
    from scipy.optimize import fsolve
    
    def mullist(a):
        mul = 1
        for i in a:
            mul = mul*i
        return mul
    
    a = [1,2,3,4,5,6,9,10]
    s = sum(a)
    so = sum(range(1,11))
    mulo = mullist(range(1,11))
    mul = mullist(a)
    over = mulo/mul
    delta = so -s
    # y = so - s -x
    # xy = mulo/mul
    def func(x):
        return (so -s -x)*x-over
    
    print int(round(fsolve(func, 0))), int(round(delta - fsolve(func, 0)))
    

    Timing it:

    $ python -mtimeit -s "$(cat with_scipy.py)" 
    
    7 8
    
    100000000 loops, best of 3: 0.0181 usec per loop
    

    Other option is:

    >>> from sets import Set
    >>> a = Set(range(1,11))
    >>> b = Set([1,2,3,4,5,6,9,10])
    >>> a-b
    Set([8, 7])
    

    And the timing is:

    Set([8, 7])
    100000000 loops, best of 3: 0.0178 usec per loop
    

提交回复
热议问题