我正在嘗試編寫超快速析因函數的代碼。我已經嘗試了一點,已經提出了以下三個候選人(除了math.factorial):Python - 快速析因函數
def f1():
return reduce(lambda x,y : x * y, xrange(1,31))
def f2():
result = 1
result *= 2
result *= 3
result *= 4
result *= 5
result *= 6
result *= 7
result *= 8
#and so-on...
result *= 28
result *= 29
result *= 30
return result
def f3():
return 1*2*3*4*5*6*7*8*9*10*11*12*13*14*15*16*17*18*19*20*21*22*23*24*25*26*27*28*29*30
我已超時這些功能。這些是結果:
In [109]: timeit f1()
100000 loops, best of 3: 11.9 µs per loop
In [110]: timeit f2()
100000 loops, best of 3: 5.05 µs per loop
In [111]: timeit f3()
10000000 loops, best of 3: 143 ns per loop
In [112]: timeit math.factorial(30)
1000000 loops, best of 3: 2.11 µs per loop
很明顯,f3()取了蛋糕。我試圖實現這一點。詳細地說,我試過寫代碼來產生這樣的字符串: 「1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 ..... ...「然後使用eval來評估這個字符串。 (承認'eval'是邪惡的)。但是,這種方法在時間上並沒有給我帶來任何收益。事實上,我花了近150微秒才完成。
請教如何推廣f3()。
我不認爲你可以概括F3。這個練習展示的是,如果你想找到最快的方法來做某件事,你需要測試實際的事情。僅適用於n = 30的測試功能無濟於事。無論如何,最後,嘗試使用'reduce'與'operator.mul'。或者,如果您可以保證參數不會超過〜1000,只需將結果緩存在列表中。 –
@AlexHall我實際上已經嘗試減少(運算符.__ mul__,....)但是,結果不是納秒範圍,這正是我所希望的。 –