Search code examples
pythonlistnumbers

Finding the longest list in given list that contains only positive numbers in Python


I am newbie to Python just for a short time. Here are my codes, which seem a little bit clumsy and I want to learn how to optimize them just because of my curiosity. Would you mind recommending to me any other shorter solutions? That would be very generous and helpful. Thanks first.

A=[-1,2,-3,2,3,-4,3,4,5,-6,-19,-20,7,8,9,10,6,8,-19,-22,-99]

front_count=0
start=0
front_position=0
end_position=0
length=0
step=0

for x in A[start:]:
    if (x>=0):
        front_count= start+ A[start:].index(x)
        step= 0
        for y in A[front_count+1:]:
          if y>=0:
            step+=1
          else:
            break
    if step>length:
        length=step
        front_position = front_count
        end_position = front_count + length

print("The longest list with positive numbers are", A[front_position:end_position+1])
    
  

The result will show up as:

The longest list with positive numbers are [7, 8, 9, 10, 6, 8]

I am expecting more other solutions to learn more about other syntax/tips/terms,.... that could be used to advance this code.


Solution

  • You can use itertools.groupby:

    from itertools import groupby
    
    A = [-1, 2, -3, 2, 3, -4, 3, 4, 5, -6, -19, -20, 7, 8, 9, 10, 6, 8, -19, -22, -99]
    
    
    max_l = []
    for k, g in groupby(A, lambda k: k > 0):
        if k:
            max_l = max(max_l, list(g), key=len)
    
    print(max_l)
    

    Prints:

    [7, 8, 9, 10, 6, 8]