[英]How can I optimize this code that uses “itertools.product” on 3 repeated dimensions? The execution times out
此代碼的目的是返回可以將 seq 拆分為三個的次數,其中所有 3 個部分的整數總和相等。 此代碼適用於測試用例,但在執行時超時。 無論如何優化for循環以使其更快?
from itertools import product
def three_split(seq):
answer=0
q=0
w=0
e=0
for i,j,k in product(range(1,len(seq)), repeat=3):
if (i+j+k==len(seq)):
q=sum(seq[:i])
w=sum(seq[i:i+j])
if q==w:
e=sum(seq[i+j:])
if w==e:
answer+=1
return(answer)
您需要比O(N^3)更好的算法。 首先,問題陳述簡單地暗示每個子序列的和必須是target = sum(seq) / 3
從計算這個目標 sum開始。 從這里開始,問題是“微不足道的”
i
的sum(seq[:i]) == target
。 這是O(N^2) ,但運行總和會將其保持為O(N) 。j
對於sum(seq[:j:]) == target
。 這也是O(N^2) ,可以保持為O(N) 。代碼:
target == sum(seq) // 3 # You might need to check that this sum is divisible by 3.
i_vals = [i for i in range(len(seq)) if sum(seq[:i]) == target]
j_vals = [j for j in range(len(seq)) if sum(seq[j:]) == target]
solution = [(i, j) for i in i_vals for j in j_vals if i <= j]
itertools.combinations
將生成所有沒有重復的唯一索引,並且生成的值要少得多。 您還需要只生成兩個值,一個用於每個要拆分的索引,因為這將生成三個列表。
像下面這樣的東西應該工作
from itertools import combinations
def three_split(seq):
answer = 0
for i, j in combinations(range(1, len(seq)), r=2):
if sum(seq[:i]) == sum(seq[i:j]) == sum(seq[j:]):
answer += 1
return answer
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.