簡體   English   中英

我如何優化以下代碼,因為它非常慢

[英]How can i optimize the following code as it is very slow

下面的代碼有哪些優化方法?

def countit(numericals=[1, 1, 2, 2, 3, 3], h=1):
     
    pol = 0
    sort = list(dict.fromkeys(numericals))
    for x in sort:
        dodaj = x + h
        for y in sort:
            if dodaj == y:
                pol = 1 + pol
            else:
                pass
 
    return pol
print(countit())

代碼檢查列表中是否有任何“對”,我的附加變量在這種情況下 h = 1。所以 h + 列表中的任何元素 = 列表中的任何元素,它是一對。

你應該能夠使用字典。 如果我正確理解了這個問題,以下內容應該可以工作。

def countit(numericals=[1, 1, 2, 2, 3, 3], h=1):
    count = 0
    d = {number:1 for number in numericals}
    
    for key in d.keys():
        count += d.get(key+h, 0)
    
    return count

dict 將所有元素存儲在numericals 然后您可以遍歷所有值並添加 h,檢查它是否也在字典中(如果不是,則默認為 0,因此我們可以求和)並且總和應該是每次您在數字中擁有元素x的計數,其中x+h也在。

應該在 O(n) 時間內運行,其中 n 是numericals列表中的元素數,因為字典訪問應該是 O(1)

嘗試這個:

def countit(numericals=[1, 1, 2, 2, 3, 3], h=1):
     
    sort = set(numericals)
    return sum(1 for x in sort for y in sort if x+h==y )
    
print(countit())

暫無
暫無

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

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