簡體   English   中英

如何使用python提高置換算法效率

[英]How to improve permutation algorithm efficiency with python

我有一個包含超過100,000個單詞的文件。 我要做的是通過字母表的每5個字母組合來計算出由最少數量的單詞使用的5個字母。

我已經制定了一個基於python的程序,最終會得到答案,但是按照它的速度,它可能需要大約48小時,如果不是更長的話。 問題的一部分在於純粹的計算數量。 我還沒有想出如何限制排列的方式,以便僅比較不同的字符串-因此僅對組合進行26 5個計算,然后將每個與100,000個單詞進行比較,得出的結果約為10 * 10 11計算最少。

有沒有辦法大幅加快這個過程,通過更有效的算法,或多線程或類似的東西?

任何關於算法效率的書籍/文章的建議也將非常感激。


我當前的程序如下:

從itertools模塊導入置換函數:

from itertools import permutations

詢問該單詞是否包含禁用字母:

def avoids (word, letters): 
    for characters in letters:
        for character in word:
            if character == characters:
                return False
    return True     

計算文件中不包含禁用字符的單詞數:

def number_of_words(file, letters):  

    open_file = open(file)

    x = 0 #counter
    for line in open_file:
        word = line.strip()
        if avoids(word, letters) == True:
        x += 1  
    return x

運行字母表中存在的五個字母的每個變體,並計算排除最少單詞的組合:

def find_smallest():

    y = 0

    #every combination of letters
    for letters in permutations("abcdefghijklmnopqrstuvwxyz", 5): 
        x = number_of_words("words.txt", letters)
        #sets y to the initial value of x
        if y == 0:
            y = x
            print "Start point, combination: %s, amount: %d" % (letters, y)

        #If current combination is greater than all previous combinations set y to x
        elif x > y:
            y = x
            combination = letters
            duplication = 0
            print "New highest, combination: %s, amount: %d" % (letters, y)

        print "%s excludes the smallest number of words (%d)" % (combination, y)

運行程序:

find_smallest()
  1. 您可以使用組合而不是排列
  2. 為什么不掃描所有單詞一次,計算每個字母的出現次數,然后選擇出現次數最少的5個呢?

這不是增加排列效率的問題。 這實際上是一個關於如何制作更智能算法的問題,它是一個數據結構問題。

我有一個包含超過100,000個單詞的文件。 我要做的是通過字母表的每5個字母組合來計算出由最少數量的單詞使用的5個字母。

循環瀏覽字母表中的26個字母,並計算列表中使用每個字母的單詞數:

import string
alphabet = string.ascii_lowercase
counts = {k: sum(k in word.lower() for word in words) for k in alphabet}

這應該是非常快的,並且應該給你足夠的信息來輕易地挑選出五個最不受歡迎的字母。

等效方法,可能比上述方法更有效,但可能不太清楚。

from itertools import chain
from collections import Counter
counter = Counter({k: 0 for k in string.ascii_lowercase})
counter.update(Counter(c for w in words for c in set(w.lower())))

暫無
暫無

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

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