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?
– Woss
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
– Carlos Storari
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 thefor
.– Woss