我想優化我的代碼以在hadoop集羣上運行。任何人都可以幫助我找到一些方法來改善這一點嗎?我正在接受一組數量超過四千萬的數字,每個數字都在一個新的線上。隨着數字讀入我計算每個數字,總結所有數字,並檢查每個數字,看看它是否是一個素數。需要更快的地圖功能
#!/usr/bin/env python
import sys
import string
import math
total_of_primes = 0
total = 0
count = 0
not_prime = 0
count_string = 'Count:'
total_string = 'Total:'
prime_string = 'Number of Primes:'
for line in sys.stdin:
try:
key = int(line)
except:
continue
total = total + key
count = count + 1
if key == 2 or key == 3:
not_prime = not_prime - 1
elif key%2 == 0 or key%3 == 0:
not_prime = not_prime + 1
else:
for i in range(5,(int(math.sqrt(key))+1),6):
if key%i == 0 or key%(i+2) ==0:
not_prime = not_prime + 1
break
total_of_primes = count - not_prime
print '%s\t%s' % (count_string,count)
print '%s\t%s' % (total_string,total)
print '%s\t%s' % (prime_string,total_of_primes)
爲什麼要*當你看到2或3時減少*合計數? – user2357112 2015-04-04 05:57:39
2和3都是素數,但1不是。 – 2015-04-04 06:29:29
是的,但如果輸入只是兩個數字2和3,你看到負兩個複合數字嗎? – user2357112 2015-04-04 06:45:13