Minimum search from a list ignoring zero values

Asked

Viewed 1,388 times

4

I have a list of values with zero elements and elements other than zero and I wanted to return the lowest value of the list and its Index, but ignoring the zeroes, that is, the fact that there are zeros does not mean that it is the lowest value but simply that it is not to be read.

So on a list like this: B=[6, 9, 4, 0, 7, 10, 2, 5, 0, 0, 0, 4, 11] i wanted to return the value 2 and in this case the index 6.

I tried to make:

for a in range(0,len(B)):
    if (B[a]!=0 and B[a]<B[a+1]):
        b_min=B[a]
        indice=a

But it doesn’t give what I want.

Can someone help me?

3 answers

3


menorNumero = min(numero for numero in B if numero != 0)
indiceDoMenorNumero = B.index(menorNumero)

I’m applying the function min, that takes the smallest value from a list to a generating expression (it would also work with a comprehensilist on). This expression can be read as "all numbers on the non-zero B list".

The function index is used to pick the position of the first occurrence of the number.

0

I don’t know if this is the best way, but it’s what I’ve been able to do with the little time I’ve had without using the functions min and index

def menorDiferenteDeZero(lista):
    menorValorIndex = -1

    for i in range(0, len(lista)):
        if(menorValorIndex == -1 or (lista[i] < lista[menorValorIndex]) and lista[i] != 0):
            menorValorIndex = i

    if menorValorIndex == -1:
        print("A lista nao contem elementos diferentes de zero")
        return

    print 'Menor index eh o {0} que tem como valor {1}'.format(menorValorIndex, lista[menorValorIndex])

lista = [6, 9, 4, 0, 7, 10, 2, 5, 0, 0, 0, 4, 11]
menorDiferenteDeZero(lista)
  • Both work, thank you very much!!!

0

Another approach, without recourse to internal functions, would be:

B=[6, 9, 4, 0, 7, 10, 2, 5, 0, 0, 0, 4, 11]

minimo = B[0]
indice = 0
contador = 0
for num in B:
    if num < minimo and num != 0:
        minimo = num
        indice = contador
    contador += 1

print "valor:", minimo
print "indice:", indice

Browser other questions tagged

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