Searching for a list minimum by ignoring zero values

4

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

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

I tried to do it:

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 does not give what I want.

Can someone help me?

    
asked by anonymous 04.04.2016 / 20:04

3 answers

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

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

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

    
04.04.2016 / 20:21
0

I do not know if this is the best way, but that's what I managed to do with the little time I 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)
    
04.04.2016 / 20:55
0

Another approach, without resorting 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
    
09.05.2016 / 11:09