Home > Back-end >  Pythonic way to detect if list contains negative values after positive values
Pythonic way to detect if list contains negative values after positive values

Time:09-21

Is there a more elegant way to detect whether values in a list are negative, then positive?

For instance [-1, 0, -2, 2] returns True as -1 is negative and the index of 2 is higher than the index of -1.

[1, 2, 3, 2] returns False as all values are positive.

[-1, -2, -3, -4] returns False as all values are negative.

[4, 3, 2, 1, -1] returns False.

This is my code for this so far:

def my_function(my_list):
    neg_index = None
    for index, item in enumerate(my_list):
        if item < 0:
            neg_index = index
        if item > 0:
            pos_index = index
            if neg_index is not None:
                if pos_index > neg_index:
                    return True

    return False

CodePudding user response:

You could use itertools.groupby:

from itertools import groupby

def positive_follows(lst):
    # get a marker for a starting negative value
    prev = False
    for key, _ in groupby(lst, lambda x: x < 0):
        # if a negative value is found, flip the marker
        # and go to the next group
        if key:
            prev = key
            continue

        # If no marker was found, then we started at
        # a positive value, so return False
        if not prev:
            return False
        else:
            # otherwise return True
            return True
    # If we only encounter negative values, then the for loop
    # will complete and we should return False
    else:
        return False


x = [-1, 0, -2, 2] # True
assert positive_follows(x)

x = [1, 2, 3, 2] # False
assert not positive_follows(x)

x = [-1, -2, -3, -4] # False
assert not positive_follows(x)

CodePudding user response:

You can use zip to process elements along with their successor:

def negThenPos(L):
    L = list(filter(None,L)) # ignore zeroes 
    return any(a<0 and b>0 for a,b in zip(L,L[1:]))

print(negThenPos([-1, 0, -2, 2]))   # True
print(negThenPos([1, 2, 3, 2]))     # False
print(negThenPos([-1, -2, -3, -4])) # False
print(negThenPos([4, 3, 2, 1, -1])) # False

CodePudding user response:

You could just loop through the list, like

a = [1, 2, 3, 4]


def Search():

  foundNeg = False

  for element in a:
    if element < 0:
      foundNeg = True
    if foundNeg:
      if element > 0:
        return True
  
  return False

print(Search())

This is not a pythonic way but it works perfectly and its time complexity is O(n) at worst

  • Related