Home > Back-end >  Get the last negative element index from list
Get the last negative element index from list

Time:02-28

I'm struggling with this one, using basic codes to get the last index of the negative element (I'm not sure how to describe this but i will leave the problem down here)

n=[1,5,-3,7,3,-1,9] => This is supposed to be random number but i will leave this list as an example
Output : n=[-2]

Please help, Thanks in advance

CodePudding user response:

for i, element in enumerate(n):
    if element < 0:
        last_negative_index = i

from_end = last_negative_index - len(n)

CodePudding user response:

Here is a way to find the index of the last negative element of a list:

idx = next((len(n)-j-1 for j in range(len(n)) if n[len(n)-j-1] < 0), None)

This approach has optimal complexity (you look at every single element of the list only once).

An alternative:

idx = next((j for j in reversed(range(len(n))) if n[j] < 0), None)

CodePudding user response:

I hope this will work.

n = [1, 5, -3, 7, 3, -1, 9]

p = [-1, 5, 3, 7, 3, 1, 9]

print(max([n.index(x) for x in n if x<0]))

print(max([n.index(y) for y in p if y<0]))

OUTPUT

5

0

If you would like to have the output as the negative indexes of the list, you may use the expression below. However, this will give all outputs as negative indexes.

n = [1, 5, -3, 7, 3, -1, 9]

print(max([n.index(x)-len(n) for x in n if x<0]))

OUTPUT

-2

CodePudding user response:

You can search with starting from the last element this will give you the last index if the negative element exists

index = len(L)
while(index>=0):
   index-=1
   if L[index]<0 :
      break
print(index-len(L))
  • Related