-2

I'm trying to print the number with the highest number of prime occurrences. but it is printing the number an the times is printed.

#checking for the highest number 
import collections
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]
counter=collections.Counter(a)
print counter.most_common(1)


#checking the number that occurs prime times


for n in a:
    times=a.count(n)
    root=times**0.5
    i=2

    while i<= root:
       if times% i != 0:
           print n
       i+=1
James Z
  • 12,209
  • 10
  • 24
  • 44

2 Answers2

1

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 poped 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])
Ma0
  • 15,057
  • 4
  • 35
  • 65
0

You can use a comprehension list to make it all easier to read

primes = [x for x in set(your_list) if all(x % y != 0 for y in range (2, x))]
max = 0
nr = -1
for x in primes:
    if primes.count(x) > max:
        max = primes.count(x)
        nr = x
BDru
  • 21
  • 3