简体   繁体   中英

Finding a value closest to the mean in a list

I have a homework and it is developing a code that will take 10 numbers from user. Then the code should add these numbers to a list. It should not add the same number twice. When 10 numbers are taken it need to calculate mean. Save the lists original form. Sort the list descending. Then it need to delete only one number closest to the mean in the list.

Here is my problem: I cant find the closest number to the mean in the list.

#I tried this:
liste.append(mean)
liste.sort()
if liste[6]-liste[5]>=liste[5]-liste[4]:
 print("Ortalamaya("+str(mean)+") en yakın sayı "+str(liste[6])+" olarak bulunmuştur.")
 liste.remove(liste[6])
 liste.remove(mean)
else:
 print("Ortalamaya("+str(mean)+") en yakın sayı "+str(liste[4])+" olarak bulunmuştur.")
 liste.remove(liste[4])
 liste.remove(mean)

It doesnt work. :(

What you did is like removing the median, not mean. To find the number closest to the mean, scan the list again (you don't need to sort it in the first place):

diff = []
for i, value in liste:
    diff.append((abs(value-mean), i))
_, i = min(diff)
liste.pop(i)

We use a list diff to store the absolute difference to the mean and the position, then find the min difference and remove that position from the liste . After that, you may add the mean to liste and sort it if that's part of your homework.

I found my questions answer today. Thanks to @adrtam so much.

(I guess I should make coding thing in English. Because I tried to translate it from Turkish to English. o_o)

Here is the answer I need;

import math

diff_list=list()
for num in numlist:
    diff=mean-num
    diff=math.fabs(diff)
    diff_list.append(diff)
print("str(numlist[diff_list.index(min(diff_list))])"+” is found as the closest number to the mean in the number list and deleted.")
numlist.pop(diff_list.index(min(diff_list)))

I created another list to save the absolute mean-number values of the numbers in number list. Then find the closest one to mean. Take its index. Then delete that index from the number list. Because they are not sorted so their index should be same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM