How about this:
a = [11,11,11,23,37,53,37,37,2,11,23,21,17,12,17,17,17,17,19,19,11,11,33,33]
def is_prime(n):
from math import sqrt
if n % 2 == 0 and n > 2:
return False
return all(n % i for i in range(3, int(sqrt(n)) + 1, 2))
counter = {k: a.count(k) for k in set(a)}
from operator import itemgetter
while True:
maximum = max(counter.items(), key=itemgetter(1))
if is_prime(maximum[1]):
break
else:
counter.pop(maximum[0])
print(maximum) # (17, 5)
print(maximum[0]) # 17
is_prime
function from here
In this case, 11
with 6 appearances is the most common but 6
is not a prime, so it gets disregarded. The second most common is 17
with 5
appearances. Since 5
is a prime, 17
is the answer.
Note that the check on whether the count
is prime is performed on the element with the max count only to minimize the checks. If it is not, the element gets pop
ed and the next one follows.
For a solution without modules you can substitute the following part of the code in:
while True:
maximum = max(counter.items(), key=lambda x: x[1])
if is_prime(maximum[1]):
break
else:
counter.pop(maximum[0])