Selection of the first number from a list

Asked

Viewed 224 times

1

Hello, I have a problem that I believe is relatively simple in python, but I can not solve it. I have a list of values that vary in positive and negative numbers. And I need to select from that list only the first positive value of when it rises from the negative. For example:

(id) - Valor
 1      -1
 2      -2
 3       1
 4       2
 5      -2
 6      -3 
 7       4
 8       5

If the list of numbers were this I would need to select only the values that are in position(id) 3 and 7. The negative and positive values that are in the positions subsequent to the first ones do not serve. For negative values I solved the problem with the following line in the code:

for i in range(len(n)):
    if n[i] > 0:

where i and n are lists I created.

If anyone has any tips, I’d appreciate it. Thank you.

  • 1

    How do id and value relate? If it were a simple list the indexes would start at 0.

  • If it’s just a list you can use zip(), Slices and list comprehensions to achieve the expected result. See this example. Not put an answer because I do not know how is the data structure you are using.

3 answers

2


Friend, you will need to control with an auxiliary variable every time the value returns to negative.
See the code below

valores = [-1,-2,1,2,-2,-3,4,5]
aux = 0
for atual in valores:
  if atual < 0:
    aux = 1
  if atual >= 0 and aux == 1:
    print(atual)
    aux = 0

The output of this program is:

1
4

You can test the code above in this link

  • @Andersoncarloswoss Really the indentation was wrong, it must have given some problem after I copied from my test in repl.it, thanks for warning!

2

There are three conditions that the number needs to meet:

  1. It can’t be the first on the list, because there won’t be any negatives before it;
  2. Must be a positive number;
  3. The immediately preceding number shall be negative;

So just check these three conditions:

numbers = [-1,-2,1,2,-2,-3,4,5]

for i, number in enumerate(numbers):
  if i > 0 and number > 0 and numbers[i-1] < 0:
    print(i)

The function enumerate return a tuple with the key pair/value of the numbers in the list and so we verify that it is not the first value (i > 0), if it is a positive value (number > 0) and whether the immediately preceding one is negative (numbers[i-1] < 0).

Remember that here the output will be 2 and 6 because the lists in Python has its index started at 0.

0

In addition to the answers above (and if the situation described by Anderson is not true) Oce could use the module itertools. Yes, it’s more complex:

def pick_first_posivite_after_negative(L):
  ia = iter(L)
  r = []

  while True:
    ia = itertools.dropwhile(lambda x: x<0, ia)
    tmp = list(itertools.islice(ia,0,1,1))
    if len(tmp) == 0:
      return r
    r.extend(tmp)
    ia = itertools.dropwhile(lambda x: x>0, ia)

The idea

First we throw out all elements in sequence that are negative (the condition is set in lambda).

Once that’s done, we have two possibilities:

1- percorremos a lista inteira, composta só de números negativos
2- paramos no primeiro número positivo após uma sequência de negativos

So we tried to get the first element of the list with the isocup. If we’re on case #1, tmp is an empty list and the function returns an empty result list. If we are in case #2, tmp will be a list of a single element, which will be added to the results list.

Then, as we already have the first positive number of the sequence, we can throw away the whole positive sequence (note that the lambda had the inequality reversed).

In the next iteration of while or we arrive at the end of the list (the negative dropwhile will return to the list as it is) or we still have a sequence of negatives.

If the first sequence of positives is to be disregarded, the last dropwhile should come before the dropwhile that discards the negatives inside the loop.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.