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)))