Find higher and lower single values Python

2

I'm trying to find the smallest and highest single value of a python array, but something is still flawed.

def pegaExtremosUnicos(v):
    i = 1
    for i in range(len(v)):
        atual = v[i]
        j = i - 1;
        while (j >=0) and (atual < v[j]):
            v[j +1] = v[j]
            j = j -1
        v[j + 1] = atual
    i = 1
    while i < len(v):
        if v[i] == v[i-1]:
            del v[i]
            del v[i-1]
        i = i +1
    d = [v[0],v[len(v)-1]]
    return tuple(d)

What was my mistake in this algorithm?

    
asked by anonymous 08.08.2016 / 01:22

2 answers

3

This can be done even using max / min, it has to define the set of values in which they will act, in this case we do not want to include the repeated elements (occurrences > 1) in this set:

vals = [123,4,5,4,6,7,8,300,200,150,300]
uniques = [i for i in vals if vals.count(i) < 2] # lista de todos os valores unicos de vals
max_value = max(uniques)
min_value = min(uniques)
print(max_value) # 200
print(min_value) # 5

Where vals.count(i) will count the number of occurrences of i in the vals list. ex: vals.count(300) in this case gives us 2 , ie neither enters our new list uniques

PS: I tested your code and put it like @zekk says in the comment, it also seems to work fine

    
08.08.2016 / 11:14
2

can be done so too: import random

def valoresUnicos(lista):
    listaSemRepetidos = []
    for i in range(len(lista)):
        if lista.count(lista[i]) == 1:
            listaSemRepetidos.append(lista[i])
    if listaSemRepetidos == []:
        return None, None
    else:
        return min(listaSemRepetidos), max(listaSemRepetidos)
    
25.08.2016 / 01:51