[英]optimise python code for random generator
您能幫我優化我的第一個python程序嗎,我正在嘗試定義一個隨機數生成器,但是以某種方式,當我放一個大數字時,它會掛起...
def rand(seed, x):
if x == 1:
return seed
elif x == 2:
return 1237
elif x == 3:
return 345892
else:
return ((31 * rand(seed, (x - 3))) + (103 * rand(seed, (x - 2))) + (7 * rand(seed, (x - 1))) + 500003) % 1000001
請嘗試:
print(rand(5, 5)), the result is : 506860
但是當您使用更大的數字時,這是一個問題,例如:
print(rand(50, 50))
您可以使用動態編程 :
def rand(seed, x):
table = [seed, 1237, 345892]
for _ in range(x - 3):
next_num = table[-3] * 31 + table[-2] * 103 + table[-1] * 7
next_num += 500003
next_num %= 1000001
table.append(next_num)
return table[-1]
之所以更快,是因為它只計算每個值一次,而您的代碼則以指數形式計算事物。
該算法為O(n)
(對於長度為x - 3
循環),而您的算法為O(1.83...^n)
( 1.83^3=1+1.83+1.83^2
)。
或者,如注釋中所建議,您可以使用functools.lru_cache
:
import functools
@functools.lru_cache()
def rand(seed, x):
# insert your code here
它的工作方式與以前的代碼幾乎相同,但是使用修飾符來記憶結果,而不是將其存儲在列表中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.