How to compare a list of numeric values with another variable in Python

0

I need to do a function that compares the values of a list with a variable, return the value of the list closest or equal to the value of the variable.

ex: The list is list = [1,2,3,7] and variable is v = 2. In this case it returns the value 2 of the list.

ex2: The list is list = [1,2,3,7] and the variable is v = 6. In this case the value 7 will be returned because it is closest.

Below is my code, calculate the mean and compare the value of the average with the list

def media(list):
som = 0
for item in list:
    som += item
med = som/len(list)
return med

def proxMed(list):
valor = 0
med = media(list)
for item in list:
    if item == trunc(med):
        valor = item
    else:
        while (med != item):
            med1 = med - 1
            med2 = med + 1
            if trunc(med1) == item:
                valor = item
                med = item
            if trunc(med2) == item:
                valor = item
                med = item
return valor

list = [1,2,6,9,7,7,1] print('A média é {:.2f}'.format(media(list))) print('O valor mais proximo da média é {}'.format(proxMed(list)))

    
asked by anonymous 14.02.2018 / 22:25

1 answer

5

If you always want to find the nearest average value, you simply compute the deviation of each value from the list against the mean, that is, the difference between the two, and check which value results in the smallest difference. For this, you can generate a dictionary that acts as a map relating the value of the list and the difference of the same before the average. This solution is valid since what is interesting to know is only the value and not its position in the list. That is, if the list has duplicate values, it will not matter which one is returned.

Thus, we define the function closest_to_average :

def closest_to_average(lst):

    """ Busca na lista o valor mais próximo da média.

    Parâmetros:
        lst list: Lista de números a ser verificada.

    Retorno:
        numérico: Valor mais próximo da média.
    """

    avg = sum(lst) / len(lst)
    diffs = {value: abs(value - avg) for value in lst}

    return min(diffs, key=diffs.get)

See working at Ideone | Repl.it

Where the average value we get by calculating the sum of the terms of the list, dividing by its size:

avg = sum(lst) / len(lst)

We also map the relationship between the values and their deviation from the mean:

diffs = {value: abs(value - avg) for value in lst}

Finally, we return the dictionary key that is related to the shortest distance to the mean. This way, doing:

print( closest_to_average([1,2,6,9,7,7,1]) ) # 6

We would have the result 6 , because the mean will be equal to 4.714285714285714 and the relation of each value with the difference will be:

{
  1: 3.7142857142857144, 
  2: 2.7142857142857144, 
  6: 1.2857142857142856, 
  9: 4.285714285714286, 
  7: 2.2857142857142856
}

Where it is possible to visually confirm that 6 is the value that has the smallest difference. Note also that the dictionary will only have a key equal to 1 and another equal to 7 , even having those values repeated in the list, as already commented in the beginning of the answer.     

14.02.2018 / 23:42