簡體   English   中英

優化代碼以查找沒有成對的索引 (i,j) 使得 i<=j 和 (a[i] +a [j]) 是 2 的和

[英]Optimised code to find no of pairs of indices (i,j) such that i<=j and (a[i] +a [j]) is a sum power of two

嘗試使用 2 個 for 循環但超時問題。Array 也可以有負元素

def pairSummingToPowerOfTwo(a):
    
    if len(a)==1 and (a[0] and (not(a[0] & (a[0] - 1))) ):
        return 1
    
    count  = 0
    for i in range(len(a)):
        for j in range(i, len(a)):

            sum = a[i] + a[j]
            if (sum and (not(sum & (sum - 1)))):
                count += 1
                        
    return count

請提出優化方法

您可以優化嵌套循環以將值直接迭代為單個循環

for x, y in itertools.combinations_with_replacement(a, 2):
    sum = x + y
    # Rest of code unchanged

處理i <= j條件而不實際產生ij ,您只需直接獲取相關值; 不必要的重復索引是一項代價高昂的任務。 您還可以采取其他措施來減少代碼行數(堆疊filter(Noneitertools.starmap(operator.add將過濾非零並將求和移動到 C 層),但它們不太可能改進性能顯着(這些操作的字節碼並不是那么低效)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM