How to compare a list of numerical values with another Python variable

Asked

Viewed 6,606 times

0

I need to do a function that compares the values of a list with a variable, returns the value of the list nearest 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 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 the nearest.

Below this my code, calculate the average 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)))

  • Will you always search for the value closest to the average or can this reference value change? Does your code work? Does it give an error? If so, which one? If not, does it produce the expected result? If not, what result did it give? What should it give?

  • I will always search closer to the average and this value can change. Only the function that calculates the average works. Yes, the logical error. Nothing appears in the second print, because the proxMed function does not work as expected. The second print does not appear when the code is executed. The value of the list closest to the average should appear

  • I did not comment in the answer the error in your solution by simply not understanding what you tried to do, mainly in the logic of while within the for.

1 answer

6


If you want to always search for the value closest to the average, you just have to calculate the deviation of each value of the list against the average, that is, the difference between both, 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 between it and the average. This solution is valid because 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 makes no difference which one will be returned.

So 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 on Ideone | Repl.it

Where the value of the average 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 average:

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

Finally, we return the key of the dictionary that is related to the shortest distance to the average. Thus, making:

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

We would have the result 6, because the average will be equal to 4.714285714285714 and the ratio of each value to the difference shall be:

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

Where it is possible to confirm visually that the 6 is the value that has the least difference. Also note that the dictionary will have only one key equal to 1 and another equal to 7, even having these values repeated in the list, as already commented at the beginning of the reply.

  • Nice code and great answer.

  • Thank you very much. I’m a beginner in this language and there’s a lot I’m still learning. By the way if you can explain me or indicate an article to understand this syntax better (diffs = {value: abs(value - avg) for value in lst}) I understood the logic but I think I need to get used to this type of structure.

  • @Carlosstorari The name of this, in English, is Dict comprehension, if you want to search about. It will generate a dictionary with the result of the expression between keys. The expression goes through the list of numbers with the for value in lst and for each value analyzes the expression on the left: value: abs(value - avg), where the first value will define the dictionary key and the result of abs() its value.

Browser other questions tagged

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