I have a list in python and I need to find the maximum occurrence of a number in a list if the number is above the average of the list.
How can I achieve this?
Thanks,
John.
I have a list in python and I need to find the maximum occurrence of a number in a list if the number is above the average of the list.
How can I achieve this?
Thanks,
John.
You can use Counter
like this
x = [1,2,4,3,2,2,4]
avg = sum(x)/len(x)
from collections import Counter
print [(num, count) for num, count in Counter(x).most_common() if num > avg]
Output
[(4, 2), (3, 1)]
Using the code from https://stackoverflow.com/a/1520716/98191 to find the most common list item:
foo = [1,8,8,4,5,6,7,8]
from itertools import groupby as g
def most_common_oneliner(L):
return max(g(sorted(L)), key=lambda(x, v):(len(list(v)),-L.index(x)))[0]
top = most_common_oneliner(foo)
if top >= max(foo):
print top
The following will output a tuple (count, element) where element is greater than the average of the list:
x = [1,2,4,3,2,2,4]
print reduce(max, [(x.count(i), i) or i in x if i > sum(x)/len(x)])
#prints (2,4)
Saving the average instead of computing it each time is a better option.