-3

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.

user2040597
  • 459
  • 2
  • 7
  • 19
  • 6
    Compute the average, and then loop through the list seeing what's bigger than the average. If you want more details than that, you should post what you've attempted so far/where you're stuck. – alecbz Nov 29 '13 at 02:28

3 Answers3

2

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)]
thefourtheye
  • 221,210
  • 51
  • 432
  • 478
0

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
Community
  • 1
  • 1
Mark Simpson
  • 2,304
  • 2
  • 22
  • 30
  • The asker wants the code to behave in such a way that if the most common value is not above the average of the numbers, then the next most common value is considered, etc. – SimonT Nov 29 '13 at 03:07
0

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.

Steve P.
  • 14,119
  • 7
  • 40
  • 71