Home > Software engineering >  Finding the longest list in given list that contains only positive numbers in Python
Finding the longest list in given list that contains only positive numbers in Python

Time:01-05

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.

CodePudding user response:

another way with O(n) is:

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

# Initialize variables
max_length = 0
max_start = 0
max_end = 0
cur_length = 0
cur_start = 0

# Iterate through the list
for i, x in enumerate(A):
    # If the current number is positive, increment the current length
    if x >= 0:
        cur_length  = 1
        # If this is the first positive number, set the start position
        if cur_length == 1:
            cur_start = i
    # If the current number is negative or the end of the list is reached,
    # check if the current sequence is the longest so far
    else:
        if cur_length > max_length:
            max_length = cur_length
            max_start = cur_start
            max_end = i - 1
        cur_length = 0

# Print the longest sequence of positive numbers
print("The longest list with positive numbers is", A[max_start:max_end 1])

CodePudding user response:

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]
  • Related