2017-08-17 42 views
-2

私は、素数が最も多い数字を印刷しようとしています。時間が印刷されている番号を印刷しています。最高の素数を持つ数字を印刷する

#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 
+2

必要なものを具体的に教えてください。期待どおりの出力と電流出力を提供できますか? – magicleon

+0

@magicleon入力がaで出力が17 17 17 17 17プロジェクトを実行してより良いアイデアを得るために出力を参照してください –

答えて

1

これはどう:

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機能ので、11 6との出演が最も一般的ですが、6が素数ではないが、この場合、

hereからそれは無視されます。次によくあるのは17で、外見は5です。 5が素数であるため、17が答えです。

countがプライムであるかどうかのチェックは、チェックを最小限に抑えるために最大カウントだけの要素に対して実行されます。そうでない場合、要素はpopとなり、次の要素が続きます。あなたが次のコードの一部を置き換えることができ、モジュールを含まない溶液の場合


while True: 
    maximum = max(counter.items(), key=lambda x: x[1]) 
    if is_prime(maximum[1]): 
     break 
    else: 
     counter.pop(maximum[0]) 
+0

それは素晴らしいアイデアですが、私の論理で私を助けることができますか?モジュールを使用してください。問題を確認してください。 –

+0

@HardipinderSinghモジュールなしアプローチも追加されました。 –

0

はあなたが作るために理解のリストを使用することができ、それは簡単にすべて読むには

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