簡體   English   中英

Python代碼片段需要很長時間才能運行..如何提高效率?

[英]Python code snippet is taking very long time to run.. how to increase efficiency?

任務是從列表(li)中選擇元素,以便總和盡可能接近給定的數字(m)!。 但是, idk 方法需要很長時間才能運行:它永遠不會完成。 當我編譯代碼時,該方法只是繼續運行和運行。

from itertools import combinations, permutations

def idk(typeOfSlices, maxNoOfPizzaSlices):
    length = len(typeOfSlices) + 1
    listToReturn = []
    temporarySum = 0

    for r in range(length):

        pool = tuple(typeOfSlices)
        n = len(pool)
        for indices in permutations(range(n), r):
            if sorted(indices) == list(indices):
                le = tuple(pool[i] for i in indices)
                ts = sum(le)
                if(ts == maxNoOfPizzaSlices):
                    print(le, ":", sum(le))
                    return le

                if(ts > temporarySum and ts <= maxNoOfPizzaSlices):
                    temporarySum = ts
                    listToreturn = le

    print(le, ":", sum(le))
    return listToReturn

m = 4500
li = [7, 12, 12, 13, 14, 28, 29, 29, 30, 32, 32, 34, 41, 45, 46, 56, 61, 61, 62, 63, 65, 68, 76, 77, 77, 92, 93, 94, 97, 103, 113, 114, 114, 120, 135, 145, 145, 149, 156, 157, 160, 169, 172, 179, 184, 185, 189, 194, 195, 195,
]
idk(li, m)

我的 2 美分...

  • 代碼片段是否適用於較小的數組大小? 如果它不適用於較小的列表,那么您可能有一個糟糕的算法。

  • 這可能是多線程的良好匹配。 您沒有修改輸入列表,因此不會有任何競爭條件。 像處理第一個 for 循環一樣將列表切片,然后讓每個線程處理排列。

  • 您對列表進行排序,然后在每次計算排列時查找重復值。 更糟糕的是,您甚至不保存排序列表。 我會創建一個專用的數據結構來存儲中間結果,這樣您就可以減少所需的排序和散列量。

暫無
暫無

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

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