How to find longest consistent increment in a python list?

前端 未结 1 1975
孤独总比滥情好
孤独总比滥情好 2021-01-24 02:56
possible_list = []
bigger_list = []

new_list= [0, 25, 2, 1, 14, 1, 14, 1, 4, 6, 6, 7, 0, 10, 11]
for i in range(0,len(new_list)):
   # if the next index is not greater          


        
相关标签:
1条回答
  • 2021-01-24 03:34

    One problem (but not the only one) with your code is that you are always adding the elements to the same possible_list, thus the lists in bigger_list are in fact all the same list!

    Instead, I suggest using [-1] to access the last element of the list of subsequences (i.e. the one to append to) and [-1][-1] to access the last element of that subsequence (for comparing the current element to).

    new_list= [0, 25, 2, 1, 14, 1, 14, 1, 4, 6, 6, 7, 0, 10, 11]    
    subseq = [[]]
    for e in new_list:
        if not subseq[-1] or subseq[-1][-1] <= e:
            subseq[-1].append(e)
        else:
            subseq.append([e])
    

    This way, subseq ends up the way you want it, and you can use max to get the longest one.

    >>> subseq
    [[0, 25], [2], [1, 14], [1, 14], [1, 4, 6, 6, 7], [0, 10, 11]]
    >>> max(subseq, key=len)
    [1, 4, 6, 6, 7]
    
    0 讨论(0)
提交回复
热议问题