In python, how does one efficiently find the largest consecutive set of numbers in a list that are not necessarily adjacent?

前端 未结 10 773

For instance, if I have a list

[1,4,2,3,5,4,5,6,7,8,1,3,4,5,9,10,11]

This algorithm should return [1,2,3,4,5,6,7,8,9,10,11].

To cl

10条回答
  •  滥情空心
    2020-12-31 12:12

    Ok, here's yet another attempt in python:

    def popper(l):
        listHolders = []
        pos = 0
        while l:
            appended = False
            item = l.pop()
            for holder in listHolders:
                if item == holder[-1][0]-1:
                    appended = True
                    holder.append((item, pos))
            if not appended:
                pos += 1
                listHolders.append([(item, pos)])
        longest = []
        for holder in listHolders:
            try:
                if (holder[0][0] < longest[-1][0]) and (holder[0][1] > longest[-1][1]):
                    longest.extend(holder)
            except:
                pass
            if len(holder) > len(longest):
                longest = holder
        longest.reverse()
        return [x[0] for x in longest]
    

    Sample inputs and outputs:

    >>> demo = list(range(50))
    >>> shuffle(demo)
    >>> demo
    [40, 19, 24, 5, 48, 36, 23, 43, 14, 35, 18, 21, 11, 7, 34, 16, 38, 25, 46, 27, 26, 29, 41, 8, 31, 1, 33, 2, 13, 6, 44, 22, 17,
     12, 39, 9, 49, 3, 42, 37, 30, 10, 47, 20, 4, 0, 28, 32, 45, 15]
    >>> popper(demo)
    [1, 2, 3, 4]
    >>> demo = [1,4,2,3,5,4,5,6,7,8,1,3,4,5,9,10,11]
    >>> popper(demo)
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
    >>>
    

提交回复
热议问题